import { NextResponse } from "next/server";
import { db } from "@/lib/db";
import { cookies } from "next/headers";
import { verifyToken } from "@/lib/auth";

// Esto evita que Next.js cachee la respuesta vieja
export const dynamic = 'force-dynamic';

export async function GET() {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get("token")?.value;
    if (!token) return NextResponse.json({ error: "No autorizado" }, { status: 401 });

    const decoded: any = verifyToken(token);
    if (!decoded || decoded.role !== 'leader') return NextResponse.json({ error: "Acceso denegado" }, { status: 403 });

    const leaderId = decoded.id;

    // CONSULTA 1: Traer brigadistas vinculados a través de la tabla militants
    const [brigadistas]: any = await db.query(
      `SELECT u.id, u.full_name, u.active 
       FROM users u
       INNER JOIN militants m ON u.militant_id = m.id
       WHERE m.leader_id = ? AND u.role = 'brigadist'`,
      [leaderId]
    );

    // CONSULTA 2: Traer militantes de cada brigadista
    const fullStructure = await Promise.all(
      brigadistas.map(async (brig: any) => {
        const [militantes]: any = await db.query(
          `SELECT * FROM militants 
           WHERE created_by = ? AND leader_id = ? 
           ORDER BY created_at DESC`,
          [brig.id, leaderId]
        );
        
        return {
          ...brig,
          active: brig.active === 1,
          militantes: militantes
        };
      })
    );

    return NextResponse.json(fullStructure);
  } catch (error) {
    console.error("STRUCTURE_API_ERROR:", error);
    return NextResponse.json({ error: "Error interno del servidor" }, { status: 500 });
  }
}