import { NextRequest, NextResponse } from 'next/server'
import pool from '@/lib/db'
import { SHEET_LIST } from '@/lib/finanzplan/types'

export async function GET(request: NextRequest) {
  // Only expose full scenario list to admin callers (bearer token)
  const secret = process.env.PITCH_ADMIN_SECRET
  const auth = request.headers.get('authorization') ?? ''
  const isAdmin = secret && auth === `Bearer ${secret}`

  // Allow callers to pass a scenarioId for row counts (e.g. investor's assigned scenario)
  const scenarioId = request.nextUrl.searchParams.get('scenarioId')

  try {
    // Investors see only the default scenario — no names of other scenarios leaked
    const scenarios = isAdmin
      ? await pool.query('SELECT * FROM fp_scenarios ORDER BY is_default DESC, name')
      : await pool.query('SELECT id FROM fp_scenarios WHERE is_default = true LIMIT 1')

    // Get row counts per sheet using the caller's scenario
    const sheets = await Promise.all(
      SHEET_LIST.map(async (s) => {
        const tableName = `fp_${s.name}`
        try {
          const { rows } = scenarioId
            ? await pool.query(
                `SELECT COUNT(*) as total, COUNT(*) FILTER (WHERE is_editable = true) as editable FROM ${tableName} WHERE scenario_id = $1`,
                [scenarioId]
              )
            : await pool.query(
                `SELECT COUNT(*) as total, COUNT(*) FILTER (WHERE is_editable = true) as editable FROM ${tableName} WHERE scenario_id = (SELECT id FROM fp_scenarios WHERE is_default = true LIMIT 1)`
              )
          return { ...s, rows: parseInt(rows[0]?.total || '0'), editable_rows: parseInt(rows[0]?.editable || '0') }
        } catch {
          return s
        }
      })
    )

    return NextResponse.json({
      sheets,
      scenarios: scenarios.rows,
      months: { start: '2026-01', end: '2030-12', count: 60, founding: '2026-08' },
    }, {
      headers: { 'Cache-Control': 'no-store' },
    })
  } catch (error) {
    return NextResponse.json({ error: String(error) }, { status: 500 })
  }
}
