import { getProjectPartyRoleThaiLabel } from './terminology';

export const PROJECT_PARTY_OPTION_CATEGORY = 'crm_project_party_role';

const LEGACY_PROJECT_PARTY_ROLE_CODE_MAP = {
  owner: 'customer',
  billing: 'billing_customer',
  consultant: 'consultant',
  contractor: 'contractor'
} as const;

export const PROJECT_PARTY_CODE_LABELS: Record<string, string> = {
  billing_customer: getProjectPartyRoleThaiLabel('billing_customer'),
  customer: getProjectPartyRoleThaiLabel('customer'),
  consultant: getProjectPartyRoleThaiLabel('consultant'),
  contractor: getProjectPartyRoleThaiLabel('contractor'),
  end_customer: getProjectPartyRoleThaiLabel('end_customer'),
  other: getProjectPartyRoleThaiLabel('other')
};

export interface ProjectPartyRoleOptionLike {
  id: string;
  code: string;
  label: string;
}

export interface ProjectPartyResolvedRole {
  id: string;
  code: string;
  label: string;
}

export function normalizeProjectPartyRoleCode(role: string | null | undefined) {
  if (!role) {
    return null;
  }

  return LEGACY_PROJECT_PARTY_ROLE_CODE_MAP[role as keyof typeof LEGACY_PROJECT_PARTY_ROLE_CODE_MAP] ?? role;
}

export function resolveProjectPartyRole(
  options: ProjectPartyRoleOptionLike[],
  role: string | null | undefined
): ProjectPartyResolvedRole | null {
  if (!role) {
    return null;
  }

  const direct = options.find((option) => option.id === role);

  if (direct) {
    return {
      id: direct.id,
      code: direct.code,
      label: direct.label
    };
  }

  const normalizedCode = normalizeProjectPartyRoleCode(role);

  if (!normalizedCode) {
    return null;
  }

  const byCode = options.find((option) => option.code === normalizedCode);

  if (!byCode) {
    return null;
  }

  return {
    id: byCode.id,
    code: byCode.code,
    label: byCode.label
  };
}

export function buildProjectPartyKey(customerId: string, roleCode: string) {
  return `${customerId}::${roleCode}`;
}
