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

// POST: Import finanzplan data (all fp_* tables) from JSON dump
export async function POST(request: NextRequest) {
  const guard = await requireAdmin(request)
  if (guard.kind === 'response') return guard.response

  try {
    const data = await request.json()
    const results: string[] = []
    const client = await pool.connect()

    try {
      await client.query('BEGIN')

      const tables = [
        'fp_scenarios', 'fp_kunden', 'fp_kunden_summary', 'fp_umsatzerloese',
        'fp_materialaufwand', 'fp_personalkosten', 'fp_betriebliche_aufwendungen',
        'fp_investitionen', 'fp_sonst_ertraege', 'fp_liquiditaet', 'fp_guv',
      ]

      for (const table of tables) {
        const rows = data[table]
        if (!rows || !Array.isArray(rows) || rows.length === 0) {
          results.push(`SKIP: ${table} (no data)`)
          continue
        }

        // Clear existing data
        await client.query(`DELETE FROM ${table}`)

        // Insert rows
        const cols = Object.keys(rows[0])
        const colNames = cols.join(', ')

        for (const row of rows) {
          const values = cols.map(c => {
            const v = row[c]
            if (v === null || v === undefined) return null
            if (typeof v === 'object') return JSON.stringify(v)
            return v
          })
          const placeholders = values.map((_, i) => `$${i + 1}`).join(', ')
          await client.query(`INSERT INTO ${table} (${colNames}) VALUES (${placeholders})`, values)
        }

        results.push(`OK: ${table} — ${rows.length} rows`)
      }

      await client.query('COMMIT')
      return NextResponse.json({ success: true, results })
    } catch (err) {
      await client.query('ROLLBACK')
      throw err
    } finally {
      client.release()
    }
  } catch (error) {
    return NextResponse.json({ error: String(error) }, { status: 500 })
  }
}
