// Shared row-assembly for the Gesamtprojekt-Export (Demo-067 C, KAR-982) —
// pure formatting helpers reused by both project-docx.ts (docx tables) and
// project-xlsx.ts (exceljs worksheets), so the two formats never drift on
// what a "Stammdaten"/"Maßnahmen" row actually contains.

import { formatNumberDe } from './docx-shared'
import type { ProjectExportStammdaten, ProjectExportWorkshopAction } from './project-types'

const EFFORT_BENEFIT_LABEL: Record<string, string> = {
  low: 'niedrig',
  middle: 'mittel',
  high: 'hoch',
}

const ACTION_STATUS_LABEL: Record<string, string> = {
  open: 'offen',
  in_progress: 'in Bearbeitung',
  done: 'erledigt',
  rejected: 'abgelehnt',
}

function deDate(iso: string | null): string {
  if (!iso) return '—'
  const d = new Date(iso)
  return Number.isNaN(d.getTime()) ? iso : d.toLocaleDateString('de-DE')
}

/** Label/value pairs for the "Stammdaten" section — shared by the DOCX
 * kvTable and the XLSX Stammdaten worksheet. */
export function stammdatenEntries(s: ProjectExportStammdaten): ReadonlyArray<readonly [string, string]> {
  return [
    ['Zulieferer', s.supplierName],
    ['Standort', s.plantLocation ?? '—'],
    ['Produkt', s.productName ?? '—'],
    ['Projekt-Code', s.projectCode ?? '—'],
    ['Fahrzeugprojekt', s.vehicleProject ?? '—'],
    ['Produktlinie', s.productLine ?? '—'],
    ['Besuchsdatum', deDate(s.visitDate)],
    ['Auftragseingang', deDate(s.orderReceivedDate)],
    ['Geplantes Ende', deDate(s.expectedEndDate)],
    ['Kundentakt', s.customerTaktTimeSec !== null ? `${formatNumberDe(s.customerTaktTimeSec, 0)} s` : '—'],
    ['Ziel-Zykluszeit', s.targetCycleTimeSec !== null ? `${formatNumberDe(s.targetCycleTimeSec, 0)} s` : '—'],
    ['Geplante OEE', s.plannedOee !== null ? `${formatNumberDe(s.plannedOee, 1)} %` : '—'],
    ['Notizen', s.notes?.trim() ? s.notes : '—'],
  ] as const
}

const WORKSHOP_ACTION_HEADERS = ['#', 'Bereich', 'Beschreibung', 'Status', 'Aufwand', 'Nutzen', 'Verantwortlich', 'Termin'] as const

export function workshopActionHeaders(): readonly string[] {
  return WORKSHOP_ACTION_HEADERS
}

export function workshopActionRow(a: ProjectExportWorkshopAction): readonly string[] {
  return [
    String(a.actionNumber),
    a.area,
    a.description,
    ACTION_STATUS_LABEL[a.status] ?? a.status,
    EFFORT_BENEFIT_LABEL[a.effort] ?? a.effort,
    EFFORT_BENEFIT_LABEL[a.benefit] ?? a.benefit,
    a.responsible ?? '—',
    deDate(a.targetDate),
  ]
}

export function formatDeDate(iso: string | null): string {
  return deDate(iso)
}
