import { NextRequest, NextResponse } from 'next/server'
import pool from '@/lib/db'
import { requireAdmin } from '@/lib/admin-auth'

export async function GET(request: NextRequest) {
  const guard = await requireAdmin(request)
  if (guard.kind === 'response') return guard.response

  const scenarios = await pool.query(
    `SELECT * FROM pitch_fm_scenarios ORDER BY is_default DESC, name`,
  )
  const assumptions = await pool.query(
    `SELECT * FROM pitch_fm_assumptions ORDER BY scenario_id, sort_order`,
  )

  const result = scenarios.rows.map(s => ({
    ...s,
    assumptions: assumptions.rows
      .filter(a => a.scenario_id === s.id)
      .map(a => ({
        ...a,
        value: typeof a.value === 'string' ? JSON.parse(a.value) : a.value,
      })),
  }))

  return NextResponse.json({ scenarios: result })
}
