import type { AuditStage, AuditStageRow } from "@/lib/api/types/auditStage.types";

function fmtDate(iso: string): string {
  if (!iso || iso.startsWith("1900")) return "—";
  try {
    return new Date(iso)
      .toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" })
      .replace(/ /g, "-");
  } catch { return "—"; }
}

// ─────────────────────────────────────────────────────────────────────────────
// mapAuditStageToRow
// Raw API AuditStage → AuditStageRow (table shape)
// ─────────────────────────────────────────────────────────────────────────────
export function mapAuditStageToRow(stage: AuditStage, index: number): AuditStageRow {
  return {
    sno:         index + 1,
    id:          stage.id,
    name:        stage.name         ?? "—",
    description: stage.description ?? "—",
    order:       stage.order        ?? 0,
    created_at:  fmtDate(stage.created_at),
    updated_at:  fmtDate(stage.updated_at),
    raw:         stage,
  };
}

// ─────────────────────────────────────────────────────────────────────────────
// mapAuditStagesToRows
// ─────────────────────────────────────────────────────────────────────────────
export function mapAuditStagesToRows(stages: AuditStage[]): AuditStageRow[] {
  return stages.map((s, i) => mapAuditStageToRow(s, i));
}

// ─────────────────────────────────────────────────────────────────────────────
// mapColumnKeyToValue
// Used by dynamic row rendering
// ─────────────────────────────────────────────────────────────────────────────
export function mapColumnKeyToValue(key: string, row: AuditStageRow): any {
  const columnMap: Record<string, any> = {
    id:          `#${row.id}`,
    name:        row.name,
    description: row.description,
    order:       row.order !== 0 ? String(row.order) : "—",
    created_at:  row.created_at,
    updated_at:  row.updated_at,
  };
  return columnMap[key] ?? row[key] ?? "—";
}
