export type OrgRankDefinition = {
  aliases: string[];
  label: string;
  weight: number;
};

export const ORG_RANK_DEFINITIONS: OrgRankDefinition[] = [
  { label: "회장", weight: -10, aliases: ["회장"] },
  { label: "사장", weight: 0, aliases: ["사장"] },
  { label: "부회장", weight: 2, aliases: ["부회장"] },
  { label: "고문", weight: 5, aliases: ["고문"] },
  { label: "부사장", weight: 10, aliases: ["부사장"] },
  { label: "전무", weight: 20, aliases: ["전무", "전무이사"] },
  { label: "상무", weight: 30, aliases: ["상무", "상무이사"] },
  { label: "이사", weight: 40, aliases: ["이사"] },
  { label: "부장", weight: 50, aliases: ["부장"] },
  { label: "수석", weight: 50, aliases: ["수석", "수석연구원"] },
  { label: "차장", weight: 60, aliases: ["차장"] },
  { label: "과장", weight: 70, aliases: ["과장"] },
  { label: "책임", weight: 70, aliases: ["책임", "책임연구원"] },
  { label: "대리", weight: 80, aliases: ["대리"] },
  { label: "선임", weight: 80, aliases: ["선임", "선임연구원"] },
  { label: "연구원", weight: 90, aliases: ["연구원"] },
  { label: "사원", weight: 90, aliases: ["사원"] },
];

const UNKNOWN_RANK_WEIGHT = 999;

function normalizeRankText(value: unknown) {
  return typeof value === "string" ? value.trim().replace(/\s+/g, "") : "";
}

export function getOrgRankDefinition(rank: unknown) {
  const normalizedRank = normalizeRankText(rank);
  if (!normalizedRank) return undefined;

  return ORG_RANK_DEFINITIONS.find((definition) =>
    definition.aliases.some(
      (alias) => normalizeRankText(alias) === normalizedRank,
    ),
  );
}

export function getOrgRankDisplayName(rank: unknown) {
  return (
    getOrgRankDefinition(rank)?.label ??
    (typeof rank === "string" ? rank.trim() : "")
  );
}

export function getOrgRankWeight(rank: unknown) {
  return getOrgRankDefinition(rank)?.weight ?? UNKNOWN_RANK_WEIGHT;
}

export function compareOrgRanks(a: unknown, b: unknown) {
  return getOrgRankWeight(a) - getOrgRankWeight(b);
}
