import 'server-only'
import { createAdminClient } from '@/lib/supabase/admin'
import { getMyParticipant, type SessionUser } from '@/lib/auth'
import { ensureParticipantContext } from '@/lib/data/auto-participants'
import { contextLabel } from '@/lib/domain/modes'
import type { Trip } from '@/types/db'

/**
 * Per-trip context gate (decision D13, Task 5.5, 2026-09-30).
 *
 * Before a trip view renders, ask which company and role the viewer acts
 * with on this trip. One matching context is stored silently; several →
 * `pending` and the page shows the chooser instead of the workspace; none
 * (no row, an admin's synthetic row, a row with no account) → nothing to
 * choose. Nothing else of the trip is sent to the client while pending.
 */
export interface TripContextChoice {
  key: string
  label: string
  role_type: string
  company_id: string | null
  company_name: string | null
}

export interface TripContextSummary {
  origin: string
  destination: string
  pickup_date: string | null
  delivery_date: string | null
  carrier_name: string | null
  broker_name: string | null
}

export interface TripContextGate {
  status: 'set' | 'none' | 'pending'
  choices: TripContextChoice[]
  /** Only loaded when the chooser is needed (A8: the dashboard summary fields). */
  summary: TripContextSummary | null
}

export async function tripContextGate(user: SessionUser, trip: Trip): Promise<TripContextGate> {
  const row = await getMyParticipant(trip.id)
  // Admin synthetic participants (no row) never see the chooser.
  if (!row) return { status: 'set', choices: [], summary: null }
  const res = await ensureParticipantContext(row, {
    id: user.id,
    originId: user.originId,
    preview: user.previewWorkspace,
    contextKey: user.contextKey,
  })
  if (res.status !== 'pending') return { status: res.status, choices: [], summary: null }
  const choices: TripContextChoice[] = (res.choices ?? []).map((c) => ({
    key: c.key,
    label: contextLabel(c),
    role_type: c.roleType,
    company_id: c.companyId,
    company_name: c.companyName,
  }))
  return { status: 'pending', choices, summary: await loadSummary(trip) }
}

/** Trip number, route, dates, carrier and broker — nothing more (A8, §16). */
async function loadSummary(trip: Trip): Promise<TripContextSummary> {
  const admin = createAdminClient()
  const { data } = await admin
    .from('trip_participants')
    .select('name, email')
    .eq('trip_id', trip.id)
    .eq('role', 'broker')
    .eq('status', 'active')
    .order('created_at')
    .limit(1)
    .maybeSingle()
  const broker = data as { name: string | null; email: string | null } | null
  return {
    origin: trip.origin,
    destination: trip.destination,
    pickup_date: trip.pickup_date ?? null,
    delivery_date: trip.delivery_date ?? null,
    carrier_name: trip.carrier_name || null,
    broker_name: broker?.name || broker?.email || null,
  }
}
