export type DeveloperAccessPage =
  | "all"
  | "overview"
  | "client_create"
  | "audit";

export const developerAccessPageOrder: DeveloperAccessPage[] = [
  "overview",
  "client_create",
  "audit",
];

export const developerAccessPageOptions: Array<{
  value: DeveloperAccessPage;
  label: string;
}> = [
  { value: "all", label: "전체" },
  { value: "overview", label: "개요" },
  { value: "client_create", label: "연동 앱 추가" },
  { value: "audit", label: "감사로그" },
];

export function normalizeDeveloperAccessPages(
  pages: Array<string | undefined | null>,
): DeveloperAccessPage[] {
  const normalized = new Set<DeveloperAccessPage>();
  for (const raw of pages) {
    const page = String(raw ?? "")
      .trim()
      .toLowerCase();
    if (!page) {
      continue;
    }
    if (page === "all") {
      return ["all"];
    }
    if (page === "overview" || page === "client_create" || page === "audit") {
      normalized.add(page);
    }
  }

  return [...developerAccessPageOrder.filter((page) => normalized.has(page))];
}

export function normalizeDeveloperAccessPageSelection(
  pages: DeveloperAccessPage[],
): DeveloperAccessPage[] {
  if (pages.includes("all")) {
    return ["all"];
  }
  const normalized = normalizeDeveloperAccessPages(pages);
  if (normalized.length === 0) {
    return ["all"];
  }
  if (normalized.length === developerAccessPageOrder.length) {
    return ["all"];
  }
  return normalized;
}

export function developerAccessPagesToLabel(pages?: Array<string | null>) {
  const normalized = normalizeDeveloperAccessPages(pages ?? []);
  if (normalized.length === 0 || normalized.includes("all")) {
    return "전체";
  }
  return normalized
    .map((page) => {
      switch (page) {
        case "overview":
          return "개요";
        case "client_create":
          return "연동 앱 추가";
        case "audit":
          return "감사로그";
        default:
          return page;
      }
    })
    .join(", ");
}

export function hasDeveloperAccessForPages(
  grantedPages: Array<string | null> | undefined,
  requiredPages: DeveloperAccessPage[],
) {
  const normalized = normalizeDeveloperAccessPages(grantedPages ?? []);
  if (normalized.includes("all")) {
    return true;
  }
  return requiredPages.some((page) => normalized.includes(page));
}

export function isDeveloperRequestPendingForPages(
  pendingPages: Array<string | null> | undefined,
  requiredPages: DeveloperAccessPage[],
) {
  const normalized = normalizeDeveloperAccessPages(pendingPages ?? []);
  if (normalized.includes("all")) {
    return true;
  }
  return requiredPages.some((page) => normalized.includes(page));
}
