"use strict";

module.exports = function (defaultFuncs, api, ctx) {
  const { parseAndCheckLogin, CustomError } = require("../utils");

  function normId(v) {
    if (v == null) return v;
    const s = String(v).trim();
    if (/^\d+$/.test(s)) return s;
    if (s[0] === "#") return s.slice(1).toLowerCase();
    if (/^[0-9a-fA-F]{6,8}$/.test(s)) return s.toLowerCase();
    return s;
  }

  const post = (url, form) =>
    defaultFuncs.post(url, ctx.jar, form).then(res => parseAndCheckLogin(ctx, defaultFuncs)(res));

  async function setTheme(themeOrColor, threadID) {
    const form = {
      dpr: 1,
      queries: JSON.stringify({
        o0: {
          doc_id: "1727493033983591",
          query_params: {
            data: {
              actor_id: ctx.i_userID || ctx.userID,
              client_mutation_id: "0",
              source: "SETTINGS",
              theme_id: normId(themeOrColor),
              thread_id: threadID
            }
          }
        }
      })
    };
    const r = await post("https://www.facebook.com/api/graphqlbatch/", form);
    const tail = r && r[r.length - 1];
    if (tail && tail.error_results > 0) throw new CustomError(r[0]?.o0?.errors || r);
    return { success: true, themeId: normId(themeOrColor) };
  }

  async function genAI(prompt) {
    const form = {
      av: ctx.userID,
      __user: ctx.userID,
      fb_api_caller_class: "RelayModern",
      fb_api_req_friendly_name: "useGenerateAIThemeMutation",
      variables: JSON.stringify({
        input: {
          actor_id: ctx.userID,
          client_mutation_id: "1",
          bypass_cache: true,
          caller: "MESSENGER",
          num_themes: 1,
          prompt
        }
      }),
      doc_id: "23873748445608673"
    };
    const data = await post("https://www.facebook.com/api/graphql/", form);
    const t = data?.data?.xfb_generate_ai_themes_from_prompt?.themes?.[0];
    if (!t?.id) throw new Error(`Không lấy được theme từ response.\nRaw=${JSON.stringify(data)}`);
    const dark = Array.isArray(t.alternative_themes) && t.alternative_themes.find(x => x?.app_color_mode === "DARK");
    return {
      themeId: t.id,
      themeName: t.accessibility_label || t.name || t.display_name || "",
      lightUrl: t?.background_asset?.image?.uri || null,
      darkUrl: dark?.background_asset?.image?.uri || null
    };
  }

  return function theme(threadID, options = {}, callback) {
    const run = async () => {
      if (!threadID) throw new Error("Thiếu threadID");
      const { themeId, aiPrompt, dryRun } = options;

      if (themeId && !aiPrompt) return setTheme(themeId, threadID);

      if (aiPrompt) {
        const info = await genAI(aiPrompt);
        if (dryRun) return { preview: true, ...info };
        const applied = await setTheme(info.themeId, threadID);
        return { success: true, ...info, apply: applied };
      }

      throw new Error("Thiếu options.aiPrompt hoặc options.themeId");
    };

    if (typeof callback === "function") run().then(d => callback(null, d)).catch(e => callback(e));
    else return run();
  };
};