import 'server-only'
import { createAdminClient } from '@/lib/supabase/admin'
import type { Permit } from '@/types/db'

export async function resolveChatPermit(tripId: string, permitId?: string | null, stateCode?: string | null): Promise<{ permit: Permit | null; error?: string }> {
  if (!permitId && !stateCode) return { permit: null }
  const admin = createAdminClient()
  let query = admin.from('permits').select('*')
  if (permitId) query = query.eq('id', permitId).eq('trip_id', tripId)
  else query = query.eq('trip_id', tripId).eq('state_code', stateCode!.toUpperCase()).order('created_at', { ascending: false }).limit(1)
  const { data, error } = await query.maybeSingle()
  if (error) return { permit: null, error: 'Could not load the selected permit.' }
  // An explicit permit button is authoritative. The client also sends its
  // current state filter, which can be stale when a user changes views; do
  // not reject the selected permit because of that auxiliary value.
  if (!data) return { permit: null, error: 'This permit selection does not belong to this trip.' }
  return { permit: data as Permit }
}
