import type { TenantSummary } from "../../../lib/adminApi";

export const ORG_UNIT_TYPE_OPTIONS = [
  "실",
  "팀",
  "TF",
  "TF팀",
  "센터",
  "디비전",
  "셀",
  "본부",
  "지역본부",
  "부",
  "임원직속",
] as const;

export const TENANT_VISIBILITY_OPTIONS = [
  { label: "공개", value: "public" },
  { label: "내부", value: "internal" },
  { label: "비공개", value: "private" },
] as const;

export type TenantVisibility =
  (typeof TENANT_VISIBILITY_OPTIONS)[number]["value"];

export type TenantOrgConfig = {
  orgUnitType: string;
  visibility: TenantVisibility;
};

const ORG_UNIT_TYPE_SET = new Set<string>(ORG_UNIT_TYPE_OPTIONS);
const TENANT_VISIBILITY_SET = new Set<string>(
  TENANT_VISIBILITY_OPTIONS.map((option) => option.value),
);

export function shouldAllowHanmacOrgConfig(
  tenant: Pick<TenantSummary, "id" | "parentId" | "slug">,
  tenants: Array<Pick<TenantSummary, "id" | "parentId" | "slug">>,
) {
  if (tenant.slug.toLowerCase() === "hanmac-family") return false;

  const byId = new Map(tenants.map((item) => [item.id, item]));
  let parentId = tenant.parentId;
  const visited = new Set<string>();

  while (parentId) {
    if (visited.has(parentId)) return false;
    visited.add(parentId);
    const parent = byId.get(parentId);
    if (!parent) return false;
    if (parent.slug.toLowerCase() === "hanmac-family") return true;
    parentId = parent.parentId;
  }

  return false;
}

export function readTenantOrgConfig(
  config: Record<string, unknown> | undefined,
): TenantOrgConfig {
  const rawVisibility = String(config?.visibility ?? "public").toLowerCase();
  const rawOrgUnitType = String(config?.orgUnitType ?? "");

  return {
    orgUnitType: ORG_UNIT_TYPE_SET.has(rawOrgUnitType) ? rawOrgUnitType : "",
    visibility: TENANT_VISIBILITY_SET.has(rawVisibility)
      ? (rawVisibility as TenantVisibility)
      : "public",
  };
}

export function mergeTenantOrgConfig(
  config: Record<string, unknown> | undefined,
  next: TenantOrgConfig,
) {
  const { orgUnitType: _orgUnitType, ...rest } = config ?? {};
  const merged = { ...rest };
  merged.visibility = next.visibility;

  if (next.orgUnitType) {
    merged.orgUnitType = next.orgUnitType;
  }

  return merged;
}

export function removeTenantOrgConfig(
  config: Record<string, unknown> | undefined,
) {
  const {
    orgUnitType: _orgUnitType,
    visibility: _visibility,
    ...rest
  } = config ?? {};
  return rest;
}
