import { NextResponse } from "next/server";
import { db } from "@/lib/db";

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const neighborhood = searchParams.get("neighborhood");
  const section = searchParams.get("section");
  const leaderId = searchParams.get("leaderId");
  const brigadistId = searchParams.get("brigadistId");

  try {
    let whereClause = "WHERE 1=1";
    let params: any[] = [];

    if (neighborhood) { whereClause += " AND neighborhood = ?"; params.push(neighborhood); }
    if (section) { whereClause += " AND section_number = ?"; params.push(section); }
    if (leaderId) { whereClause += " AND leader_id = ?"; params.push(leaderId); }
    if (brigadistId) { whereClause += " AND brigadist_id = ?"; params.push(brigadistId); }

    // Conteos generales
    const [stats]: any = await db.query(`
      SELECT 
        COUNT(*) as total,
        COUNT(CASE WHEN role = 'leader' THEN 1 END) as leaders,
        COUNT(CASE WHEN role = 'brigadist' THEN 1 END) as brigadists,
        COUNT(CASE WHEN role IS NULL OR role = 'militant' THEN 1 END) as militants
      FROM militants
      ${whereClause}
    `, params);

    return NextResponse.json(stats[0]);
  } catch (error) {
    return NextResponse.json({ error: "Error en reportes" }, { status: 500 });
  }
}