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

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 body = await request.json().catch(() => ({}))
  const name = body.name || ''

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

  const forkName = name.trim() || `${parent.rows[0].name} (fork)`

  const { rows } = await pool.query(
    `INSERT INTO pitch_versions (name, parent_id, status, created_by)
     VALUES ($1, $2, 'draft', $3) RETURNING *`,
    [forkName, id, adminId],
  )
  const version = rows[0]

  await copyVersionData(id, version.id, adminId)
  await logAdminAudit(adminId, 'version_forked', {
    version_id: version.id,
    parent_id: id,
    parent_name: parent.rows[0].name,
    name: forkName,
  }, request)

  return NextResponse.json({ version })
}
