import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import jwt from "jsonwebtoken";
import { db } from "@/lib/db";

const SECRET = process.env.JWT_SECRET!;

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

    const sessionUser: any = jwt.verify(token, SECRET);
    const userId = sessionUser.id;

    let query = `
      SELECT 
        m.id, m.first_name, m.last_name_paternal, m.neighborhood, 
        m.latitude, m.longitude, u.role, m.created_by
      FROM militants m
      LEFT JOIN users u ON m.id = u.militant_id
      WHERE m.latitude IS NOT NULL AND m.longitude IS NOT NULL
    `;
    
    let params: any[] = [];
    if (scope === "mine") {
      query += " AND m.created_by = ?";
      params.push(userId);
    }

    const [rows]: any = await db.query(query, params);
    return NextResponse.json(rows);
  } catch (error) {
    return NextResponse.json({ error: "Error en mapa" }, { status: 500 });
  }
}