import { NextResponse } from 'next/server'
import { getSessionUser } from '@/lib/auth'
import { createAdminClient } from '@/lib/supabase/admin'
import { canSeePermitCost, redactCostsForPilot } from '@/lib/domain/permit-cost'
import { normalizeStateCatalog } from '@/lib/domain/state-catalog'

export async function GET(_req: Request, ctx: { params: Promise<{ code: string }> }) {
  const user = await getSessionUser()
  if (!user) return NextResponse.json({ error: 'Sign in first.' }, { status: 401 })
  const { code } = await ctx.params
  const normalized = code.trim().toUpperCase()
  if (!/^[A-Z]{2}$/.test(normalized)) return NextResponse.json({ error: 'Invalid state code.' }, { status: 400 })
  const { data, error } = await createAdminClient().from('all_states')
    .select('state_code,state_name,details,synced_at')
    .eq('state_code', normalized).eq('is_canonical', true).eq('source_present', true).maybeSingle()
  if (error) return NextResponse.json({ error: 'Could not load state information. Please try again.' }, { status: 503 })
  if (!data) return NextResponse.json({ error: 'No state information has been published for this state.' }, { status: 404 })
  const catalog = normalizeStateCatalog(data)
  if (!canSeePermitCost(user.role)) {
    catalog.information.pricing = []
    catalog.provisions.pricing = []
    for (const topics of [catalog.information, catalog.provisions]) {
      for (const sections of Object.values(topics)) {
        for (const section of sections) {
          for (const item of section.items) item.detail = redactCostsForPilot(item.detail)
        }
      }
    }
  }
  return NextResponse.json(catalog, { headers: { 'Cache-Control': 'private, no-store' } })
}
