import { NextRequest, NextResponse } from 'next/server'
import pool from '@/lib/db'
import { computeFinanzplan } from '@/lib/finanzplan/engine'
import { validateAdminSecret } from '@/lib/auth'

export async function POST(request: NextRequest) {
  if (!validateAdminSecret(request)) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }
  try {
    const body = await request.json().catch(() => ({}))
    const scenarioId = body.scenarioId

    // Get scenario ID
    let sid = scenarioId
    if (!sid) {
      const { rows } = await pool.query('SELECT id FROM fp_scenarios WHERE is_default = true LIMIT 1')
      if (rows.length === 0) {
        return NextResponse.json({ error: 'No default scenario found' }, { status: 404 })
      }
      sid = rows[0].id
    }

    const result = await computeFinanzplan(pool, sid)

    return NextResponse.json({
      scenarioId: sid,
      computed: true,
      summary: {
        total_revenue_y2026: result.umsatzerloese.total.m1 !== undefined
          ? Object.values(result.umsatzerloese.total).reduce((a, b) => a + b, 0)
          : 0,
        total_costs_y2026: Object.values(result.betriebliche.total_gesamt).reduce((a, b) => a + b, 0),
        headcount_m60: result.personalkosten.headcount.m60 || 0,
        cash_balance_m60: result.liquiditaet.endstand.m60 || 0,
      },
    })
  } catch (error) {
    console.error('Finanzplan compute error:', error)
    return NextResponse.json({ error: 'Compute failed' }, { status: 500 })
  }
}
