import { NextRequest, NextResponse } from 'next/server'
import pool from '@/lib/db'
import { requireAdmin, logAdminAudit, hashPassword, revokeAllAdminSessions } 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 actorAdminId = guard.kind === 'admin' ? guard.admin.id : null

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

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

  const updates: string[] = []
  const params: unknown[] = []
  let p = 1

  if (typeof name === 'string' && name.trim()) {
    updates.push(`name = $${p++}`)
    params.push(name.trim())
  }
  if (typeof is_active === 'boolean') {
    updates.push(`is_active = $${p++}`)
    params.push(is_active)
  }
  if (typeof password === 'string') {
    if (password.length < 12) {
      return NextResponse.json({ error: 'password must be at least 12 characters' }, { status: 400 })
    }
    const hash = await hashPassword(password)
    updates.push(`password_hash = $${p++}`)
    params.push(hash)
  }

  if (updates.length === 0) {
    return NextResponse.json({ error: 'no fields to update' }, { status: 400 })
  }

  updates.push(`updated_at = NOW()`)
  params.push(id)

  const { rows } = await pool.query(
    `UPDATE pitch_admins SET ${updates.join(', ')}
     WHERE id = $${p}
     RETURNING id, email, name, is_active, last_login_at, created_at`,
    params,
  )

  // If deactivated or password changed, revoke their sessions
  if (is_active === false || typeof password === 'string') {
    await revokeAllAdminSessions(id)
  }

  const action = is_active === false ? 'admin_deactivated' : 'admin_edited'
  await logAdminAudit(
    actorAdminId,
    action,
    {
      target_admin_id: id,
      target_email: before.rows[0].email,
      before: before.rows[0],
      after: { name: rows[0].name, is_active: rows[0].is_active },
      password_changed: typeof password === 'string',
    },
    request,
  )

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