import 'server-only'

import { createAdminClient } from '@/lib/supabase/admin'
import { computePermitWarnings } from '@/lib/domain/warnings'
import { diffExpiryWarnings, EXPIRY_KINDS, type StoredExpiryWarning } from '@/lib/domain/expiry-recheck'
import type { Permit, Trip } from '@/types/db'

/**
 * Recompute expired / expiring alerts for every trip still in progress
 * (not completed or cancelled). Run daily (scripts/permit-expiry-recheck.mjs).
 * Other alert kinds are never touched.
 */
export async function recheckPermitExpiry(now: Date = new Date()): Promise<{ trips: number; permits: number; added: number; removed: number }> {
  const admin = createAdminClient()
  const { data: trips, error: tripError } = await admin.from('trips').select('*').not('status', 'in', '(completed,cancelled)')
  if (tripError) throw new Error(`expiry recheck trips: ${tripError.message}`)
  const tripRows = (trips ?? []) as Trip[]
  if (!tripRows.length) return { trips: 0, permits: 0, added: 0, removed: 0 }
  const tripIds = tripRows.map((t) => t.id)
  const { data: permits, error: permitError } = await admin.from('permits').select('*').in('trip_id', tripIds)
  if (permitError) throw new Error(`expiry recheck permits: ${permitError.message}`)
  const permitRows = (permits ?? []) as Permit[]
  const byTrip = new Map<string, Permit[]>()
  for (const p of permitRows) byTrip.set(p.trip_id, [...(byTrip.get(p.trip_id) ?? []), p])

  const computed = tripRows.flatMap((trip) => {
    const siblings = byTrip.get(trip.id) ?? []
    return siblings.flatMap((permit) => computePermitWarnings(trip, permit, now, siblings)
      .filter((w) => (EXPIRY_KINDS as readonly string[]).includes(w.kind))
      .map((w) => ({ ...w, tripId: trip.id })))
  })
  const { data: existing, error: warnError } = await admin.from('warnings')
    .select('id, permit_id, kind, message').in('trip_id', tripIds).in('kind', [...EXPIRY_KINDS]).eq('resolved', false)
  if (warnError) throw new Error(`expiry recheck warnings: ${warnError.message}`)
  const { add, removeIds } = diffExpiryWarnings((existing ?? []) as StoredExpiryWarning[], computed)

  if (removeIds.length) {
    const { error } = await admin.from('warnings').delete().in('id', removeIds)
    if (error) throw new Error(`expiry recheck delete: ${error.message}`)
  }
  if (add.length) {
    const { error } = await admin.from('warnings').insert(add.map((w) => ({
      trip_id: w.tripId, permit_id: w.permitId ?? null, kind: w.kind, severity: w.severity, message: w.message,
    })))
    if (error) throw new Error(`expiry recheck insert: ${error.message}`)
  }
  return { trips: tripRows.length, permits: permitRows.length, added: add.length, removed: removeIds.length }
}
