import { createAdminClient } from '@/lib/supabase/admin'
import { getVisibleTrips } from '@/lib/data/trips'
import type { RoutePurchaseRow } from '@/app/billing/billing-preview'

/**
 * Route purchase history for the Billing & Wallet view — the user's route
 * requests across their trips. Shared by /billing and the pilot dispatch
 * dashboard's Billing / Plan tab (Nash, 2026-09-12: "he should be able to
 * handle his billing from here").
 */
export async function loadRoutePurchases(user: Parameters<typeof getVisibleTrips>[0]): Promise<RoutePurchaseRow[]> {
  const { trips } = await getVisibleTrips(user)
  if (trips.length === 0) return []
  const admin = createAdminClient()
  const { data } = await admin
    .from('service_requests')
    .select('id, trip_id, state_code, status, route_type, requester_label, created_at')
    .in('trip_id', trips.map((t) => t.id))
    .eq('type', 'route_request')
    .order('created_at', { ascending: false })
    .limit(12)
  const tripLabel = new Map(trips.map((t) => [t.id, `${t.origin || '?'} → ${t.destination || '?'}`]))
  return (data ?? []).map((r) => ({
    id: r.id,
    state_code: r.state_code,
    status: r.status,
    route_type: r.route_type,
    requester_label: r.requester_label,
    created_at: r.created_at,
    trip_label: tripLabel.get(r.trip_id) ?? '',
  }))
}
