import { NextRequest, NextResponse } from 'next/server'
import pool from '@/lib/db'
import { requireAdmin, logAdminAudit } from '@/lib/admin-auth'
import { snapshotBaseTables, copyVersionData } from '@/lib/version-helpers'

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

  const { rows } = await pool.query(`
    SELECT v.*,
           a.name AS created_by_name, a.email AS created_by_email,
           (SELECT COUNT(*)::int FROM pitch_investors i WHERE i.assigned_version_id = v.id) AS assigned_count
    FROM pitch_versions v
    LEFT JOIN pitch_admins a ON a.id = v.created_by
    ORDER BY v.created_at DESC
  `)

  return NextResponse.json({ versions: rows })
}

export async function POST(request: NextRequest) {
  const guard = await requireAdmin(request)
  if (guard.kind === 'response') return guard.response
  const adminId = guard.kind === 'admin' ? guard.admin.id : null

  const body = await request.json().catch(() => ({}))
  const { name, description, parent_id } = body

  if (!name || typeof name !== 'string') {
    return NextResponse.json({ error: 'name required' }, { status: 400 })
  }

  // Create the version row
  const { rows } = await pool.query(
    `INSERT INTO pitch_versions (name, description, parent_id, status, created_by)
     VALUES ($1, $2, $3, 'draft', $4) RETURNING *`,
    [name.trim(), description || null, parent_id || null, adminId],
  )
  const version = rows[0]

  // Copy data from parent or snapshot base tables
  if (parent_id) {
    await copyVersionData(parent_id, version.id, adminId)
  } else {
    await snapshotBaseTables(version.id, adminId)
  }

  await logAdminAudit(adminId, 'version_created', {
    version_id: version.id,
    name: version.name,
    parent_id: parent_id || null,
  }, request)

  return NextResponse.json({ version })
}
