import { normalizeAdminAccountKind } from "@/lib/admin-account-kind";
import type { AdminProfile } from "@/types/api/admin-auth";
import type { AdminNavItem } from "@/modules/_config/admin-nav";

const KEY = "lottery_admin_profile";

export function readProfile(): AdminProfile | null {
  if (typeof window === "undefined") {
    return null;
  }
  const raw = window.localStorage.getItem(KEY);
  if (!raw) {
    return null;
  }
  try {
    const v = JSON.parse(raw) as AdminProfile;
    if (
      typeof v?.id === "number" &&
      typeof v?.username === "string" &&
      typeof v?.nickname === "string"
    ) {
      const permissions = Array.isArray(v.permissions)
        ? v.permissions.filter((s): s is string => typeof s === "string")
        : [];
      const operationalPermissions = Array.isArray(v.operational_permissions)
        ? v.operational_permissions.filter((s): s is string => typeof s === "string")
        : [];
      const navigation = Array.isArray(v.navigation)
        ? v.navigation.filter((item): item is AdminNavItem => {
            return (
              item !== null &&
              typeof item === "object" &&
              typeof item.segment === "string" &&
              typeof item.label === "string" &&
              typeof item.href === "string"
            );
          })
        : [];
      const accountKind = normalizeAdminAccountKind(
        typeof v.account_kind === "string" ? v.account_kind : undefined,
      );
      return {
        id: v.id,
        username: v.username,
        nickname: v.nickname,
        email: typeof v.email === "string" || v.email === null ? v.email : null,
        permissions,
        operational_permissions: operationalPermissions,
        navigation,
        is_super_admin: v.is_super_admin === true ? true : undefined,
        account_kind: accountKind,
      };
    }
  } catch {
    /* ignore */
  }

  return null;
}

export function writeProfile(p: AdminProfile | null): void {
  if (typeof window === "undefined") {
    return;
  }
  if (p) {
    window.localStorage.setItem(KEY, JSON.stringify(p));
  } else {
    window.localStorage.removeItem(KEY);
  }
}
