import { normalizeAdminAccountKind } from "@/lib/admin-account-kind";
import {
  adminHasAnyPermission,
  adminHasAnyPermissionCode,
  adminOperationalPermissionCodes,
} from "@/lib/admin-permissions";
import { useAdminProfile } from "@/stores/admin-session";
import type { AdminAccountKind, AdminProfile } from "@/types/api/admin-auth";

export function resolveAdminAccountKind(profile: AdminProfile | null | undefined): AdminAccountKind | null {
  if (!profile) {
    return null;
  }
  const normalized = normalizeAdminAccountKind(profile.account_kind);
  if (normalized) {
    return normalized;
  }
  if (profile.is_super_admin) {
    return "super_admin";
  }
  if (profile.agent != null) {
    return "agent_operator";
  }
  if (profile.site != null) {
    return "site_admin";
  }
  return "platform_account";
}

/** 统一权限与会话身份读取：legacy `prd.*` 与 action code 并存，新代码优先用 `hasAnyCode`。 */
export function useAdminPermission() {
  const profile = useAdminProfile();
  const legacyPermissions = profile?.permissions ?? [];
  const operationalPermissions = adminOperationalPermissionCodes(profile);

  return {
    profile,
    legacyPermissions,
    operationalPermissions,
    accountKind: resolveAdminAccountKind(profile),
    isSuperAdmin: profile?.is_super_admin === true,
    /** @deprecated 逐步改用 {@link hasAnyCode} */
    hasAnyLegacy: (required: readonly string[]) => adminHasAnyPermission(legacyPermissions, required),
    hasAnyCode: (required: readonly string[]) => adminHasAnyPermissionCode(operationalPermissions, required),
  };
}
