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

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

  const body = await request.json().catch(() => ({}))
  const { investor_id } = body

  if (!investor_id) {
    return NextResponse.json({ error: 'investor_id required' }, { status: 400 })
  }

  const { rows } = await pool.query(
    `UPDATE pitch_investors SET status = 'revoked', updated_at = NOW()
     WHERE id = $1 RETURNING email`,
    [investor_id],
  )

  if (rows.length === 0) {
    return NextResponse.json({ error: 'Investor not found' }, { status: 404 })
  }

  await revokeAllSessions(investor_id)
  await logAdminAudit(adminId, 'investor_revoked', { email: rows[0].email }, request, investor_id)

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