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

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

export async function PATCH(request: NextRequest, ctx: RouteContext) {
  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, color } = body

  if (name === undefined && description === undefined && color === undefined) {
    return NextResponse.json({ error: 'name, description, or color required' }, { status: 400 })
  }

  const before = await pool.query(
    `SELECT name, description, color FROM pitch_fm_scenarios WHERE id = $1`,
    [id],
  )
  if (before.rows.length === 0) {
    return NextResponse.json({ error: 'Scenario not found' }, { status: 404 })
  }

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

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

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