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

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

  await runDataCleanup()

  const { rows } = await pool.query(
    `SELECT i.id, i.email, i.name, i.company, i.status, i.last_login_at, i.login_count, i.created_at,
            i.first_activity_at, i.data_masked_at,
            i.assigned_version_id, v.name AS version_name,
            (SELECT COUNT(*) FROM pitch_audit_logs a WHERE a.investor_id = i.id AND a.action = 'slide_viewed') as slides_viewed,
            (SELECT MAX(a.created_at) FROM pitch_audit_logs a WHERE a.investor_id = i.id) as last_activity
     FROM pitch_investors i
     LEFT JOIN pitch_versions v ON v.id = i.assigned_version_id
     ORDER BY i.created_at DESC`,
  )

  return NextResponse.json({ investors: rows })
}
