import { defineStore } from "pinia";
import {
  fetchCurrentMenus,
  fetchFilePresignDownload,
  fetchPlatformCurrentMenus,
  fetchSwitchableTenants,
} from "../api/modules";
import { PERMS } from "../constants/permissions";
import { useAuthStore } from "./auth";

export type MenuItem = {
  menuName: string;
  routePath: string;
};

export type TenantOption = {
  tenantId: number;
  tenantCode: string;
  tenantName: string;
  logoUrl?: string;
  current?: boolean;
};

const fallbackMenus: MenuItem[] = [];
const platformMenus: MenuItem[] = [
  { menuName: "租户管理", routePath: "/platform/tenants" },
  { menuName: "平台用户管理", routePath: "/platform/users" },
  { menuName: "平台角色管理", routePath: "/platform/roles" },
  { menuName: "通知网关配置", routePath: "/platform/notify-gateways" },
  { menuName: "专家管理", routePath: "/platform/experts" },
  { menuName: "平台字典管理", routePath: "/platform/dictionaries" },
  { menuName: "平台会话管理", routePath: "/platform/auth-sessions" },
  { menuName: "平台审计日志", routePath: "/platform/audit-logs" },
  { menuName: "平台菜单与权限", routePath: "/platform/menus" },
];
const platformRouteWhitelist = new Set(platformMenus.map((item) => item.routePath));

export const useMenuStore = defineStore("menu", {
  state: () => ({
    menus: [] as MenuItem[],
    tenantLogoDisplay: "",
    switchableTenants: [] as TenantOption[],
    tenantSwitching: false,
  }),
  getters: {
    useTopMenuLayout: (state): boolean => state.menus.length > 0 && state.menus.length <= 5,
  },
  actions: {
    reset() {
      this.menus = [];
      this.tenantLogoDisplay = "";
      this.switchableTenants = [];
      this.tenantSwitching = false;
    },
    setTenantSwitching(next: boolean) {
      this.tenantSwitching = next;
    },
    async loadTenantLogo() {
      const authStore = useAuthStore();
      this.tenantLogoDisplay = "";
      if (authStore.scope !== "TENANT") {
        return;
      }
      const tenantLogo = authStore.currentTenantLogo;
      if (!tenantLogo) {
        return;
      }
      if (tenantLogo.startsWith("http://") || tenantLogo.startsWith("https://")) {
        this.tenantLogoDisplay = tenantLogo;
        return;
      }
      try {
        const resp = await fetchFilePresignDownload({ objectKey: tenantLogo });
        this.tenantLogoDisplay = String(resp?.data?.signedUrl || "");
      } catch (_e) {
        this.tenantLogoDisplay = "";
      }
    },
    async loadMenus() {
      const authStore = useAuthStore();
      if (authStore.scope === "PLATFORM") {
        try {
          const resp = await fetchPlatformCurrentMenus();
          const list = Array.isArray(resp?.data) ? resp.data : [];
          const normalized = list
            .map((item: any) => ({
              menuName: String(item?.routePath || "") === "/platform/permissions" ? "平台菜单与权限" : String(item?.menuName || ""),
              routePath: String(item?.routePath || "") === "/platform/permissions" ? "/platform/menus" : String(item?.routePath || ""),
            }))
            .filter((item: MenuItem) => platformRouteWhitelist.has(item.routePath));
          const deduped = normalized.filter((item, index, arr) => arr.findIndex((row) => row.routePath === item.routePath) === index);
          this.menus = deduped.length > 0 ? deduped : platformMenus;
        } catch (_e) {
          this.menus = platformMenus;
        }
        return;
      }

      try {
        const resp = await fetchCurrentMenus();
        const list = Array.isArray(resp?.data) ? resp.data : [];
        const resolved = list.length > 0 ? list : fallbackMenus;
        const normalized = resolved.map((item: any) => ({
          menuName: String(item?.routePath || "") === "/permissions" ? "菜单与权限" : String(item?.menuName || ""),
          routePath: String(item?.routePath || "") === "/permissions" ? "/menus" : String(item?.routePath || ""),
        }));
        const hasMenuEntry = normalized.some((item: MenuItem) => item.routePath === "/menus");
        const canSeeMenuPage = authStore.hasPermission(PERMS.role.read) || authStore.hasPermission(PERMS.permission.read);
        if (canSeeMenuPage && !hasMenuEntry) {
          normalized.push({ menuName: "菜单与权限", routePath: "/menus" });
        }
        this.menus = normalized.filter((item: MenuItem, index: number, arr: MenuItem[]) =>
          arr.findIndex((row) => row.routePath === item.routePath) === index,
        );
      } catch (_e) {
        this.menus = fallbackMenus;
      }
    },
    async loadSwitchableTenants() {
      const authStore = useAuthStore();
      const canSwitchTenant = authStore.scope === "TENANT" && authStore.hasPermission(PERMS.tenant.switch);
      if (!canSwitchTenant) {
        this.switchableTenants = [];
        return;
      }
      try {
        const resp = await fetchSwitchableTenants();
        this.switchableTenants = Array.isArray(resp?.data) ? resp.data : [];
      } catch (_e) {
        this.switchableTenants = [];
      }
    },
    async refreshContext() {
      await this.loadTenantLogo();
      await this.loadMenus();
      await this.loadSwitchableTenants();
    },
  },
});
