import { NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { getAppOrg } from '@/lib/org'
import {
  getEffectiveUser,
  getViewAsImportScope,
} from '@/lib/effective-user'
import { readFiltersFromSearchParams } from '@/lib/filters'

/**
 * GET /projects/expand?operator=…&client=…&project=…&{filter params}
 *
 * Returns the description-level breakdown for one (operator, client,
 * project) group, scoped to the same filter that the /projects table is
 * showing. The client uses the sentinel `__null__` for any of the three
 * group keys that's actually NULL on the row.
 *
 * Response: `[{ description, row_count, billout_seconds, cost_usd }, ...]`
 */
export async function GET(request: Request) {
  try {
    const supabase = await createClient()
    const org = await getAppOrg(supabase)
    if (!org) {
      return NextResponse.json({ error: 'org not found' }, { status: 404 })
    }

    const eu = await getEffectiveUser(supabase, org.id)
    const viewAsScope = await getViewAsImportScope(supabase, org.id, eu)

    const url = new URL(request.url)
    const sp: Record<string, string> = {}
    for (const [k, v] of url.searchParams) sp[k] = v

    const opRaw = sp.operator ?? ''
    const clRaw = sp.client ?? ''
    const prRaw = sp.project ?? ''
    const operator = opRaw === '__null__' ? null : opRaw
    const client = clRaw === '__null__' ? null : clRaw
    const project = prRaw === '__null__' ? null : prRaw

    const {
      startBound,
      endBound,
      status,
      batch,
      q,
      project: projectQ,
      user,
      source_email,
      client: clientQ,
      operator: operatorQ,
      imported_by,
    } = readFiltersFromSearchParams(sp, { date: 'all', status: 'all' })

    const missingInfo = sp.missing_info === '1'
    const effectiveImportedBy = viewAsScope
      ? eu!.effective_user_id
      : imported_by

    const { data, error } = await supabase.rpc(
      'project_entries_by_description',
      {
        p_org_id: org.id,
        p_operator: operator,
        p_client: client,
        p_project: project,
        p_start: startBound,
        p_end: endBound,
        p_status: status,
        p_batch: batch,
        p_q: q,
        p_project_q: projectQ,
        p_user: user,
        p_source_email: source_email,
        p_client_q: clientQ,
        p_operator_q: operatorQ,
        p_imported_by: effectiveImportedBy,
        p_missing_info: missingInfo,
      },
    )
    if (error) {
      console.error('[projects/expand] rpc failed', error)
      return NextResponse.json({ error: error.message }, { status: 500 })
    }

    type Row = {
      description: string | null
      row_count: number
      billout_seconds: number
      cost_usd: number | string
    }
    const rows = ((data as Row[] | null) ?? []).map((r) => ({
      description: r.description,
      rowCount: Number(r.row_count ?? 0),
      billoutSeconds: Number(r.billout_seconds ?? 0),
      cost: Number(r.cost_usd ?? 0),
    }))
    return NextResponse.json(rows)
  } catch (err) {
    console.error('[projects/expand] failed', err)
    const msg = err instanceof Error ? err.message : String(err)
    return NextResponse.json({ error: msg }, { status: 500 })
  }
}
