import type { ComputedWarning } from '@/lib/domain/warnings'

/**
 * Daily expiry re-check (2026-10-06). Expiry used to be checked only when a
 * permit was read, so a permit valid at upload never became "expired". The
 * re-check recomputes expiry alerts for trips still in progress and returns
 * what to add and what to remove. Pure, so the rule is testable.
 */
export interface StoredExpiryWarning { id: string; permit_id: string | null; kind: string; message: string }

export const EXPIRY_KINDS = ['expired', 'expiring'] as const

const key = (permitId: string | null | undefined, kind: string, message: string) => `${permitId ?? ''}|${kind}|${message}`

export function diffExpiryWarnings(
  existing: StoredExpiryWarning[],
  computed: Array<ComputedWarning & { tripId: string }>,
): { add: Array<ComputedWarning & { tripId: string }>; removeIds: string[] } {
  const wanted = new Map(computed.map((w) => [key(w.permitId, w.kind, w.message), w]))
  const have = new Set(existing.map((w) => key(w.permit_id, w.kind, w.message)))
  return {
    add: [...wanted.entries()].filter(([k]) => !have.has(k)).map(([, w]) => w),
    removeIds: existing.filter((w) => !wanted.has(key(w.permit_id, w.kind, w.message))).map((w) => w.id),
  }
}
