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

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

export async function GET(request: NextRequest, ctx: Ctx) {
  const guard = await requireAdmin(request)
  if (guard.kind === 'response') return guard.response

  const { id } = await ctx.params
  const { rows } = await pool.query(
    `SELECT r.id, r.investor_id, r.released_by, r.released_at,
            i.email, i.name, i.company, i.data_masked_at
     FROM dataroom_releases r
     JOIN pitch_investors i ON i.id = r.investor_id
     WHERE r.document_id = $1
     ORDER BY r.released_at DESC`,
    [id],
  )
  return NextResponse.json({ releases: rows })
}

export async function POST(request: NextRequest, ctx: Ctx) {
  const guard = await requireAdmin(request)
  if (guard.kind === 'response') return guard.response

  const { id } = await ctx.params
  const admin = await getAdminFromCookie()
  const { investor_ids } = await request.json() as { investor_ids: string[] }

  if (!Array.isArray(investor_ids) || investor_ids.length === 0) {
    return NextResponse.json({ error: 'investor_ids required' }, { status: 400 })
  }

  const inserted: string[] = []
  for (const investorId of investor_ids) {
    const { rowCount } = await pool.query(
      `INSERT INTO dataroom_releases (document_id, investor_id, released_by)
       VALUES ($1, $2, $3)
       ON CONFLICT (document_id, investor_id) DO NOTHING`,
      [id, investorId, admin?.email ?? 'admin'],
    )
    if (rowCount) inserted.push(investorId)
  }

  if (inserted.length > 0) {
    await logAudit(null, 'dataroom_document_released', { document_id: id, investor_ids: inserted }, request, undefined, undefined, admin?.id)
  }
  return NextResponse.json({ released: inserted.length })
}
