export type HanmacFamilyOrderTenant = {
  name: string;
  slug: string;
};

export const HANMAC_FAMILY_ROOT_SLUG = "hanmac-family";

export const HANMAC_FAMILY_TENANT_ORDER = [
  "gpdtdc",
  "saman",
  "hanmac",
  "baron-group",
] as const;

function normalizedTenantText(tenant: HanmacFamilyOrderTenant) {
  return `${tenant.slug} ${tenant.name}`.trim().toLowerCase();
}

export function isHanmacFamilyRootTenant(tenant: HanmacFamilyOrderTenant) {
  return (
    tenant.slug.toLowerCase() === HANMAC_FAMILY_ROOT_SLUG ||
    tenant.name.includes("한맥가족")
  );
}

export function getHanmacFamilyTenantOrderRank(
  tenant: HanmacFamilyOrderTenant,
) {
  const text = normalizedTenantText(tenant);
  if (text.includes("gpdtdc") || text.includes("총괄기획")) return 0;
  if (text.includes("saman") || text.includes("삼안")) return 1;
  if (
    (text.includes("hanmac") || text.includes("한맥기술")) &&
    !isHanmacFamilyRootTenant(tenant)
  ) {
    return 2;
  }
  if (text.includes("baron-group") || text.includes("바론그룹")) return 3;
  return Number.MAX_SAFE_INTEGER;
}

export function compareHanmacFamilyTenants<T extends HanmacFamilyOrderTenant>(
  a: T,
  b: T,
) {
  const rankDiff =
    getHanmacFamilyTenantOrderRank(a) - getHanmacFamilyTenantOrderRank(b);
  if (rankDiff !== 0) return rankDiff;
  return a.name.localeCompare(b.name);
}

export function orderHanmacFamilyTenants<T extends HanmacFamilyOrderTenant>(
  tenants: readonly T[],
) {
  return [...tenants].sort(compareHanmacFamilyTenants);
}

export function orderHanmacFamilyChildren<T extends HanmacFamilyOrderTenant>(
  parent: HanmacFamilyOrderTenant,
  children: readonly T[],
) {
  return isHanmacFamilyRootTenant(parent)
    ? orderHanmacFamilyTenants(children)
    : [...children];
}
