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

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

  const { searchParams } = new URL(request.url)
  const investorId = searchParams.get('investor_id')
  const targetInvestorId = searchParams.get('target_investor_id')
  const adminId = searchParams.get('admin_id')
  const actorType = searchParams.get('actor_type')      // 'admin' | 'investor'
  const action = searchParams.get('action')
  const since = searchParams.get('since')               // ISO date
  const until = searchParams.get('until')
  const limit = Math.min(parseInt(searchParams.get('limit') || '100'), 500)
  const offset = parseInt(searchParams.get('offset') || '0')

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

  if (investorId) {
    conditions.push(`a.investor_id = $${p++}`)
    params.push(investorId)
  }
  if (targetInvestorId) {
    conditions.push(`a.target_investor_id = $${p++}`)
    params.push(targetInvestorId)
  }
  if (adminId) {
    conditions.push(`a.admin_id = $${p++}`)
    params.push(adminId)
  }
  if (actorType === 'admin') {
    conditions.push(`a.admin_id IS NOT NULL`)
  } else if (actorType === 'investor') {
    conditions.push(`a.investor_id IS NOT NULL`)
  }
  if (action) {
    conditions.push(`a.action = $${p++}`)
    params.push(action)
  }
  if (since) {
    conditions.push(`a.created_at >= $${p++}`)
    params.push(since)
  }
  if (until) {
    conditions.push(`a.created_at <= $${p++}`)
    params.push(until)
  }

  const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''

  const { rows } = await pool.query(
    `SELECT a.*,
            i.email AS investor_email, i.name AS investor_name,
            ti.email AS target_investor_email, ti.name AS target_investor_name,
            ad.email AS admin_email, ad.name AS admin_name
     FROM pitch_audit_logs a
     LEFT JOIN pitch_investors i ON i.id = a.investor_id
     LEFT JOIN pitch_investors ti ON ti.id = a.target_investor_id
     LEFT JOIN pitch_admins ad ON ad.id = a.admin_id
     ${where}
     ORDER BY a.created_at DESC
     LIMIT $${p++} OFFSET $${p++}`,
    [...params, limit, offset],
  )

  const totalRes = await pool.query(
    `SELECT COUNT(*)::int AS total FROM pitch_audit_logs a ${where}`,
    params,
  )

  return NextResponse.json({ logs: rows, total: totalRes.rows[0].total })
}
