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

interface Ctx { params: Promise<{ versionId: string }> }

export async function GET(request: NextRequest, ctx: Ctx) {
  // Admin-only: verify admin session
  const admin = await getAdminFromCookie()
  if (!admin) {
    return NextResponse.json({ error: 'Admin access required for preview' }, { status: 401 })
  }

  const { versionId } = await ctx.params

  // Load version metadata
  const ver = await pool.query(
    `SELECT name, status FROM pitch_versions WHERE id = $1`,
    [versionId],
  )
  if (ver.rows.length === 0) {
    return NextResponse.json({ error: 'Version not found' }, { status: 404 })
  }

  // Load version data
  const { rows } = await pool.query(
    `SELECT table_name, data FROM pitch_version_data WHERE version_id = $1`,
    [versionId],
  )

  if (rows.length === 0) {
    return NextResponse.json({ error: 'Version has no data' }, { status: 404 })
  }

  const map: Record<string, unknown[]> = {}
  for (const row of rows) {
    map[row.table_name] = typeof row.data === 'string' ? JSON.parse(row.data) : row.data
  }

  // Return PitchData format + version metadata
  return NextResponse.json({
    company: (map.company || [])[0] || null,
    team: map.team || [],
    financials: map.financials || [],
    market: map.market || [],
    competitors: map.competitors || [],
    features: map.features || [],
    milestones: map.milestones || [],
    metrics: map.metrics || [],
    funding: (map.funding || [])[0] || null,
    products: map.products || [],
    fp_scenarios: map.fm_scenarios || [],
    fm_assumptions: map.fm_assumptions || [],
    _version: { name: ver.rows[0].name, status: ver.rows[0].status },
  })
}
