import { JobApplication } from "./types";

type SalaryFields = Pick<JobApplication, "salary" | "salaryMin" | "salaryMax" | "salaryCurrency" | "salaryPeriod">;

const PERIOD_SUFFIX: Record<string, string> = { year: "yr", month: "mo", hour: "hr" };

/** Structured salary when present ("60 000–70 000 NOK/yr"), otherwise the free-text field. */
export function formatSalary(job: SalaryFields): string | null {
  const { salaryMin, salaryMax, salaryCurrency, salaryPeriod } = job;
  if (salaryMin == null && salaryMax == null) {
    return job.salary?.trim() || null;
  }

  const fmt = (value: number) => value.toLocaleString();
  const range = salaryMin != null && salaryMax != null && salaryMin !== salaryMax
    ? `${fmt(salaryMin)}–${fmt(salaryMax)}`
    : fmt((salaryMin ?? salaryMax) as number);
  const currency = salaryCurrency ? ` ${salaryCurrency}` : "";
  const period = salaryPeriod ? `/${PERIOD_SUFFIX[salaryPeriod] ?? salaryPeriod}` : "";
  return `${range}${currency}${period}`;
}
