import client, { createUeuse } from "@/lib/client";
import Memory from "@/lib/memory";
import ueuseModule from "better-uwuzu-sdk/types/1.6.8/types/modules/ueuse";
import i18next from "i18next";
import MiQ from "miq";
import { EOL } from "node:os";

export default async function miqCommand(ueuse: ueuseModule, args: string[]) {
  if (!args[1]) {
    await createUeuse({
      text: i18next.t("lackOption", { command: "miq" }),
      replyid: ueuse.uniqid,
    }, "オプションが不足している旨");

    return;
  }

  let mem = Memory.memory;

  switch (args[1]) {
    case "generate":
      const itUeuse = await client.request("ueuse/get", {
        uniqid: ueuse.replyid,
      });

      if (!itUeuse.success || !itUeuse.data[0]) {
        console.warn("返信元のユーズの取得に失敗:", "error_code" in itUeuse
          ? itUeuse.error_code
          : "データなし");

        await createUeuse({
          text: i18next.t("replySourceFailed"),
          replyid: ueuse.uniqid,
        }, "ソースが見つからない旨");

        return;
      }

      mem = Memory.memory;
      const permission = mem["permissions"][itUeuse.data[0].account.userid] ?? "consent";
      switch (permission) {
        case "me":
          if (itUeuse.data[0].account.userid !== ueuse.account.userid) {
            await createUeuse({
              text: i18next.t("miqPermissionMe"),
              replyid: ueuse.uniqid,
            }, "権限が自分自身のみである旨");

            return;
          }
        case "consent":
          if (itUeuse.data[0].account.userid !== ueuse.account.userid) {
            await createUeuse({
              text: i18next.t("miqPermissionConsent", { userid: itUeuse.data[0].account.userid }),
              replyid: ueuse.uniqid,
            }, "権限が許可制である旨");

            return;
          }
      }

      const result = await MiQ({
        type: "Base64Data",
        color: (args[2] ?? "") === "color",
        text: itUeuse.data[0].text,
        iconURL: itUeuse.data[0].account.user_icon,
        userid: itUeuse.data[0].account.userid,
        username: itUeuse.data[0].account.username,
      });

      if (!(typeof result === "string")) {
        await createUeuse({
          text: i18next.t("miqGenerateFailed"),
          replyid: ueuse.uniqid,
        }, "Make it a Quoteの生成に失敗した旨");

        return;
      }

      await createUeuse({
        text: i18next.t("miqSuccess", { message: (args[2] ?? "") === "color"
            ? "カラーモードで生成しました。"
            : "モノクロモードで生成しました。"
          }),
        media: {
          photo: [result],
        },
        replyid: ueuse.uniqid,
      }, "Make it a Quote");

      break;
    case "permission":
      if (args[2] === undefined) {
        mem = Memory.memory;
        const permission = mem["permissions"][ueuse.account.userid] ?? "consent";

        await createUeuse({
          text: i18next.t("permissionResponse", { permission }),
          replyid: ueuse.uniqid,
        }, "権限");

        return;
      }

      const availablePermission = ["me", "everyone", "consent"];
      if (!(availablePermission.includes(args[2]))) {
        await createUeuse({
          text: i18next.t("invalidOption", { option: args[2], command: "miq" }),
          replyid: ueuse.uniqid,
        }, "無効なオプションである旨");

        return;
      }

      {
        mem = Memory.memory;
        mem["permissions"][ueuse.account.userid] = args[2];
        Memory.memory = mem;

        await createUeuse({
          text: i18next.t("permissionChangeSuccess", { username: ueuse.account.username, permission: args[2] }),
          replyid: ueuse.uniqid,
        }, "権限の変更に成功した旨");
      }

      break;
    case "allow":
      if (ueuse.replyid === "") {
        await createUeuse({
          text: i18next.t("injusticeFormat"),
          replyid: ueuse.uniqid,
        }, "形式が異なる旨");

        return;
      }

      {
        mem = Memory.memory;
        const permission = mem["permissions"][ueuse.account.userid] ?? "consent";

        if (permission !== "consent") {
          await createUeuse({
            text: i18next.t("permisionIsNotConsent"),
            replyid: ueuse.uniqid,
          }, "権限が許可制ではない旨");

          return;
        }
      }

      const confirmUeuse = await client.request("ueuse/get", {
        uniqid: ueuse.replyid,
      });

      if (!confirmUeuse.success || !confirmUeuse.data[0]) {
        console.warn("返信元のユーズの取得に失敗:", "error_code" in confirmUeuse
          ? confirmUeuse.error_code
          : "データなし");

        await createUeuse({
          text: i18next.t("replySourceFailed"),
          replyid: ueuse.uniqid,
        }, "ソースが見つからない旨");

        return;
      }

      if (confirmUeuse.data[0].replyid === "") {
        await createUeuse({
          text: i18next.t("injusticeFormat"),
          replyid: ueuse.uniqid,
        }, "形式が異なる旨");

        return;
      }

      mem = Memory.memory;
      if (confirmUeuse.data[0].account.userid !== mem["userid"]) {
        console.warn("返信元のユーズがBotではない:", "error_code" in confirmUeuse
          ? confirmUeuse.error_code
          : "データなし");

        await createUeuse({
          text: i18next.t("replySourceIsNotThis"),
          replyid: ueuse.uniqid,
        }, "返信元がこのBotではない旨");

        return;
      }

      const requestUeuse = await client.request("ueuse/get", {
        uniqid: confirmUeuse.data[0].replyid,
      });

      if (!requestUeuse.success || !requestUeuse.data[0]) {
        console.warn("返信元のユーズの取得に失敗:", "error_code" in requestUeuse
          ? requestUeuse.error_code
          : "データなし");

        await createUeuse({
          text: i18next.t("replySourceFailed"),
          replyid: ueuse.uniqid,
        }, "ソースが見つからない旨");

        return;
      }

      if (requestUeuse.data[0].replyid === "") {
        await createUeuse({
          text: i18next.t("injusticeFormat"),
          replyid: ueuse.uniqid,
        }, "形式が異なる旨");
        return;
      }

      const sourceUeuse = await client.request("ueuse/get", {
        uniqid: requestUeuse.data[0].replyid,
      });

      if (!sourceUeuse.success || !sourceUeuse.data[0]) {
        console.warn("返信元のユーズの取得に失敗:", "error_code" in sourceUeuse
          ? sourceUeuse.error_code
          : "データなし");

        await createUeuse({
          text: i18next.t("replySourceFailed"),
          replyid: ueuse.uniqid,
        }, "ソースが見つからない旨");

        return;
      }

      if (sourceUeuse.data[0].account.userid !== ueuse.account.userid) {
        await createUeuse({
          text: i18next.t("replySourceIsNotSourceUser"),
          replyid: ueuse.uniqid,
        }, "ソースのユーズと/miq allowのユーザーが一致しない旨");

        return;
      }

      {
        mem = Memory.memory;
        let text = requestUeuse.data[0].text;
        text = text.replace(`@${mem.userid}`, "");
        text = text.trim();

        const rows = text.split(/\r\n|\r|\n/).map(row => row.trim());
        const commandRow = rows.filter(row => row.startsWith("/"))[0];

        if (!commandRow || commandRow === "") {
          console.warn("コマンドが本文から参照できません");

          await createUeuse({
            text: i18next.t("commandNotFound"),
            replyid: requestUeuse.data[0].uniqid,
          }, "コマンドが見つからない旨");

          await createUeuse({
            text: i18next.t("injusticeFormat"),
            replyid: ueuse.uniqid,
          }, "形式が異なる旨");

          break;
        }

        const requestUeuseArgs = commandRow.replace("/", "").split(" ");

        const result = await MiQ({
          type: "Base64Data",
          color: (requestUeuseArgs[2] ?? "") === "color",
          text: sourceUeuse.data[0].text,
          iconURL: sourceUeuse.data[0].account.user_icon,
          userid: sourceUeuse.data[0].account.userid,
          username: sourceUeuse.data[0].account.username,
        });

        if (!(typeof result === "string")) {
          await createUeuse({
            text: i18next.t("miqGenerateFailed"),
            replyid: ueuse.uniqid,
          }, "Make it a Quoteの生成に失敗した旨");

          return;
        }

        await createUeuse({
          text: i18next.t("miqSuccess", { message: ((requestUeuseArgs[2] ?? "") === "color"
                ? "カラーモードで生成しました。"
                : "モノクロモードで生成しました。")
              + EOL + `@${requestUeuse.data[0].account.userid}`,
            }),
          media: {
            photo: [result],
          },
          replyid: ueuse.uniqid,
        }, "Make it a Quote");
      }

      break;
  }
}