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

export async function GET() {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get("token")?.value;

    if (!token) {
      return NextResponse.json({ error: "Sesión no válida" }, { status: 401 });
    }

    const decoded: any = verifyToken(token);
    if (!decoded || decoded.role !== "brigadist") {
      return NextResponse.json({ error: "No autorizado" }, { status: 403 });
    }

    const userId = decoded.id;

    // 1. VERIFICACIÓN DE BLOQUEO (Solo tabla users)
    const [userCheck]: any = await db.query(
      "SELECT active FROM users WHERE id = ?",
      [userId]
    );

    if (!userCheck[0] || userCheck[0].active === 0) {
      return NextResponse.json({ error: "BLOCKED" }, { status: 403 });
    }

    // 2. OBTENER MILITANTES
    const [militants]: any = await db.query(
      "SELECT * FROM militants WHERE created_by = ? AND status != 'inactive' ORDER BY created_at DESC",
      [userId],
    );

    // 3. OBTENER LA SECCIÓN (Buscamos la sección del último militante registrado)
    let sectionForMap = null;
    if (militants.length > 0) {
      sectionForMap = militants[0].section_number; 
    }

    // 4. OBTENER METAS
    const goalsQuery = `
      SELECT 
        g.*,
        IFNULL((
          SELECT COUNT(*) 
          FROM militants m 
          WHERE m.created_by = ? 
          AND m.status != 'inactive'
          AND m.created_at BETWEEN g.start_date AND g.end_date
        ), 0) as current_progress
      FROM goals g
      WHERE g.end_date >= CURDATE()
      AND (g.user_id = ? OR g.user_id IS NULL)
      ORDER BY g.created_at DESC
    `;
    const [goals]: any = await db.query(goalsQuery, [userId, userId]);

    // --- NUEVO: OBTENER TODAS LAS SECCIONES DISPONIBLES DEL MUNICIPIO 8 ---
    const [availableSections]: any = await db.query(
      "SELECT DISTINCT section_number FROM sections ORDER BY section_number ASC"
    );

    return NextResponse.json({
      militants,
      goals,
      userName: decoded.name,
      section_number: sectionForMap,
      // Enviamos el array simple de números de sección
      availableSections: availableSections.map((s: any) => s.section_number) 
    });

  } catch (error) {
    console.error("BRIGADIST_GET_ERROR:", error);
    return NextResponse.json({ error: "Error de servidor" }, { status: 500 });
  }
}