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

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

export async function POST(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 })
  if (ver.rows[0].status === 'committed') {
    return NextResponse.json({ error: 'Already committed' }, { status: 400 })
  }

  const { rows } = await pool.query(
    `UPDATE pitch_versions SET status = 'committed', committed_at = NOW() WHERE id = $1 RETURNING *`,
    [id],
  )

  await logAdminAudit(adminId, 'version_committed', {
    version_id: id,
    name: rows[0].name,
  }, request)

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