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

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

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

  const { id } = await ctx.params

  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
     WHERE v.id = $1`,
    [id],
  )
  if (rows.length === 0) return NextResponse.json({ error: 'Not found' }, { status: 404 })

  const data = await loadVersionData(id)

  return NextResponse.json({ version: rows[0], data })
}

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

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

  const before = await pool.query(`SELECT name, description, status FROM pitch_versions WHERE id = $1`, [id])
  if (before.rows.length === 0) return NextResponse.json({ error: 'Not found' }, { status: 404 })
  if (before.rows[0].status === 'committed') {
    return NextResponse.json({ error: 'Cannot edit a committed version' }, { status: 400 })
  }

  const { rows } = await pool.query(
    `UPDATE pitch_versions SET name = COALESCE($1, name), description = COALESCE($2, description)
     WHERE id = $3 RETURNING *`,
    [name ?? null, description ?? null, id],
  )

  await logAdminAudit(adminId, 'version_edited', {
    version_id: id,
    before: { name: before.rows[0].name, description: before.rows[0].description },
    after: { name: rows[0].name, description: rows[0].description },
  }, request)

  return NextResponse.json({ version: rows[0] })
}

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

  const { id } = await ctx.params

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

  // Prevent deleting committed versions that have children or assigned investors
  if (ver.rows[0].status === 'committed') {
    const children = await pool.query(`SELECT id FROM pitch_versions WHERE parent_id = $1 LIMIT 1`, [id])
    if (children.rows.length > 0) {
      return NextResponse.json({ error: 'Cannot delete: has child versions' }, { status: 400 })
    }
    const investors = await pool.query(`SELECT id FROM pitch_investors WHERE assigned_version_id = $1 LIMIT 1`, [id])
    if (investors.rows.length > 0) {
      return NextResponse.json({ error: 'Cannot delete: assigned to investors' }, { status: 400 })
    }
  }

  await pool.query(`DELETE FROM pitch_versions WHERE id = $1`, [id])
  await logAdminAudit(adminId, 'version_deleted', { version_id: id, name: ver.rows[0].name }, request)

  return NextResponse.json({ success: true })
}
