"use strict";

const utils = require("../utils");
const log = require("npmlog");

/**
 * GỘP: Generate AI Theme (graphql) + Apply Theme (graphqlbatch như changeThreadColor)
 * ENV override:
 *   - FB_DOCID_GEN_AI_THEME (default: "23873748445608673")        [CHƯA XÁC MINH]
 *   - FB_DOCID_SET_THREAD_THEME_BATCH (default: "1727493033983591") [CHƯA XÁC MINH]
 */
module.exports = function (defaultFuncs, api, ctx) {
  const GRAPHQL = "https://www.facebook.com/api/graphql/";
  const GRAPHQL_BATCH = "https://www.facebook.com/api/graphqlbatch/";

  const DOCID_GEN_AI_THEME =
    process.env.FB_DOCID_GEN_AI_THEME || "23873748445608673"; // [CHƯA XÁC MINH]
  const DOCID_SET_THREAD_THEME_BATCH =
    process.env.FB_DOCID_SET_THREAD_THEME_BATCH || "1727493033983591"; // [CHƯA XÁC MINH]

  function normalizeThemeId(input) {
    if (input == null) return input;
    const s = String(input).trim();
    if (/^\d+$/.test(s)) return s;                  // theme ID dạng số
    if (s.startsWith("#")) return s.slice(1).toLowerCase(); // hex -> bỏ '#', lowercase
    if (/^[0-9a-fA-F]{6,8}$/.test(s)) return s.toLowerCase(); // hex thuần
    return s;
  }

  async function postGraphQL(form) {
    const res = await defaultFuncs.post(GRAPHQL, ctx.jar, form);
    return utils.parseAndCheckLogin(ctx, defaultFuncs)(res);
  }

  function applyThemeBatch(themeOrColor, threadID) {
    // giữ nguyên kiểu changeThreadColor (Promise + callback ở hàm ngoài)
    const theme_id = normalizeThemeId(themeOrColor);
    const form = {
      dpr: 1,
      queries: JSON.stringify({
        o0: {
          // doc_id cho graphqlbatch (theme/color)
          doc_id: DOCID_SET_THREAD_THEME_BATCH, // [CHƯA XÁC MINH]
          query_params: {
            data: {
              actor_id: ctx.i_userID || ctx.userID,
              client_mutation_id: "0",
              source: "SETTINGS",
              theme_id,           // có thể là ID số hoặc mã hex (lowercase)
              thread_id: threadID
            }
          }
        }
      })
    };

    log.info("AITheme", `Applying theme via graphqlbatch: theme_id=${theme_id}, thread=${threadID}`);

    return defaultFuncs
      .post(GRAPHQL_BATCH, ctx.jar, form)
      .then(utils.parseAndCheckLogin(ctx, defaultFuncs))
      .then(resData => {
        const tail = resData && resData[resData.length - 1];
        if (tail && tail.error_results > 0) {
          const detail = resData[0]?.o0?.errors || resData;
          throw new utils.CustomError(detail);
        }
        return { success: true, theme_id };
      });
  }

  // Hàm chính: sinh AI theme -> áp theme bằng graphqlbatch
  return function theme(threadID, options = {}, callback) {
    const aiPrompt = options.aiPrompt || "anime";

    let resolveFunc = () => {};
    let rejectFunc = () => {};
    const returnPromise = new Promise((resolve, reject) => {
      resolveFunc = resolve;
      rejectFunc = reject;
    });

    const cb =
      typeof callback === "function"
        ? callback
        : (err, data) => (err ? rejectFunc(err) : resolveFunc(data));

    (async () => {
      try {
        if (!threadID) throw new Error("Thiếu threadID");

        // Step 1: Generate AI Theme (RelayModern)
        const genForm = {
          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: aiPrompt
            }
          }),
          doc_id: DOCID_GEN_AI_THEME // [CHƯA XÁC MINH]
        };

        log.info("AITheme", `Đang tạo theme AI với prompt: ${aiPrompt}`);

        const genRes = await postGraphQL(genForm);
        log.info("AITheme", `Phản hồi tạo theme: ${JSON.stringify(genRes)}`);

        let themeID;
        try {
          themeID = genRes.data.xfb_generate_ai_themes_from_prompt.themes[0].id;
        } catch (e) {
          throw new Error(
            `Không lấy được theme_id từ response generate.\nRaw=${JSON.stringify(genRes)}`
          );
        }

        log.info("AITheme", `🎨 Generated theme_id = ${themeID}`);

        // Step 2: Apply Theme bằng graphqlbatch (như changeThreadColor)
        const applyRes = await applyThemeBatch(themeID, threadID);

        log.info("AITheme", "✅ Applied AI Theme successfully (graphqlbatch)");
        cb(null, { success: true, themeId: themeID, apply: applyRes });
      } catch (err) {
        log.error("AITheme", "❌ Error: " + err.message);
        cb(err);
      }
    })();

    return returnPromise;
  };
};