// QAF Baseline selection (KAR-799, spec B5).
//
// "Oldest vs newest" is only the DEFAULT. When the order can't be established
// confidently (missing or equal quotation dates, unknown manual ids), we still
// PROPOSE a deterministic ALT/NEU but flag status = 'baseline_review' so the UI
// asks the user instead of silently choosing (spec B5).
//
// Net-new: the existing board uses fixed manual version slots. Pure — operates
// on file refs, not on parsed content.

export interface QafFileRef {
  id: string
  fileName: string
  /** ISO quotation date from the summary sheet, or null when absent. */
  quotationDate: string | null
  /** ISO upload timestamp — secondary ordering key. */
  uploadedAt?: string | null
}

export type BaselineMode = 'oldest_vs_newest' | 'manual'

export type BaselineStatus = 'ok' | 'baseline_review' | 'insufficient'

export interface BaselineSelection {
  altId: string | null
  neuId: string | null
  status: BaselineStatus
  reason: string
}

export interface BaselineOptions {
  mode?: BaselineMode
  manualAltId?: string
  manualNeuId?: string
}

function time(value: string | null | undefined): number | null {
  if (!value) return null
  const t = Date.parse(value)
  return Number.isNaN(t) ? null : t
}

/** Stable order key: quotation date, then upload time, then file name. */
function orderTriplet(f: QafFileRef): [number, number, string] {
  return [time(f.quotationDate) ?? Number.POSITIVE_INFINITY, time(f.uploadedAt) ?? Number.POSITIVE_INFINITY, f.fileName]
}

function compareRefs(a: QafFileRef, b: QafFileRef): number {
  const [qa, ua, na] = orderTriplet(a)
  const [qb, ub, nb] = orderTriplet(b)
  if (qa !== qb) return qa - qb
  if (ua !== ub) return ua - ub
  return na < nb ? -1 : na > nb ? 1 : 0
}

export function selectBaseline(files: QafFileRef[], opts: BaselineOptions = {}): BaselineSelection {
  if (files.length < 2) {
    return { altId: null, neuId: null, status: 'insufficient', reason: 'Mindestens zwei QAFs nötig.' }
  }

  if (opts.mode === 'manual') {
    const altOk = files.some((f) => f.id === opts.manualAltId)
    const neuOk = files.some((f) => f.id === opts.manualNeuId)
    if (altOk && neuOk && opts.manualAltId !== opts.manualNeuId) {
      return { altId: opts.manualAltId!, neuId: opts.manualNeuId!, status: 'ok', reason: 'Manuelle Baseline-Auswahl.' }
    }
    return {
      altId: altOk ? opts.manualAltId! : null,
      neuId: neuOk ? opts.manualNeuId! : null,
      status: 'baseline_review',
      reason: 'Manuelle Auswahl unvollständig oder ungültig — bitte Baseline prüfen.',
    }
  }

  const sorted = [...files].sort(compareRefs)
  const alt = sorted[0]
  const neu = sorted[sorted.length - 1]

  const altDate = time(alt.quotationDate)
  const neuDate = time(neu.quotationDate)

  let status: BaselineStatus = 'ok'
  let reason = 'Älteste QAF als ALT, neueste als NEU (nach Angebotsdatum).'

  if (altDate === null || neuDate === null) {
    status = 'baseline_review'
    reason = 'Angebotsdatum fehlt — Reihenfolge über Upload/Dateiname geschätzt, bitte Baseline prüfen.'
  } else if (altDate === neuDate) {
    status = 'baseline_review'
    reason = 'Gleiches Angebotsdatum bei ALT und NEU — bitte Baseline prüfen.'
  }

  return { altId: alt.id, neuId: neu.id, status, reason }
}
