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!;
const LOCATIONIQ_TOKEN = process.env.LOCATIONIQ_TOKEN;

type TokenPayload = {
  id: number;
  role: "admin" | "leader" | "brigadist";
  name: string;
};

/**
 * Geocodificación usando LocationIQ.
 */
async function getCoordinates(street: string, ext_number: string, neighborhood: string, cp: string) {
  if (!LOCATIONIQ_TOKEN) {
    console.warn("⚠️ No se encontró LOCATIONIQ_TOKEN.");
    return { lat: null, lng: null };
  }

  const cleanAddress = [
    `${street} ${ext_number || ""}`.trim(),
    neighborhood,
    cp,
    "Emiliano Zapata",
    "Morelos",
    "Mexico"
  ].filter(Boolean).join(", ");

  try {
    const url = `https://us1.locationiq.com/v1/search?key=${LOCATIONIQ_TOKEN}&q=${encodeURIComponent(cleanAddress)}&format=json&limit=1`;
    const response = await fetch(url);
    if (!response.ok) return { lat: null, lng: null };
    
    const data = await response.json();
    if (data && data.length > 0) {
      return { lat: parseFloat(data[0].lat), lng: parseFloat(data[0].lon) };
    }
  } catch (error) {
    console.error("Error en LocationIQ:", error);
  }
  return { lat: null, lng: null };
}

export async function POST(req: Request) {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get("token")?.value;

    if (!token) return NextResponse.json({ error: "No autenticado" }, { status: 401 });

    let sessionUser: TokenPayload;
    try {
      sessionUser = jwt.verify(token, SECRET) as TokenPayload;
    } catch {
      return NextResponse.json({ error: "Sesión expirada o inválida" }, { status: 401 });
    }

    const data = await req.json();

    // --- LÓGICA PIRAMIDAL AUTOMÁTICA ---
    let leader_id = null;
    let brigadist_id = null;
    const created_by = sessionUser.id;

    if (sessionUser.role === 'leader') {
      leader_id = sessionUser.id;
    } else if (sessionUser.role === 'brigadist') {
      brigadist_id = sessionUser.id;
      const [userRecord]: any = await db.query(
        "SELECT leader_id FROM users WHERE id = ? LIMIT 1",
        [sessionUser.id]
      );
      if (userRecord && userRecord.length > 0) {
        leader_id = userRecord[0].leader_id;
      }
    }

    // Geocoding
    const { lat, lng } = await getCoordinates(
      data.street || "", 
      data.ext_number || "", 
      data.neighborhood || "", 
      data.postal_code || ""
    );

    // --- INSERCIÓN CON MANEJO DE DUPLICADOS ---
    const [result]: any = await db.query(
      `INSERT INTO militants (
        first_name, last_name_paternal, last_name_maternal, birth_date, sex,
        curp, elector_key, section_number, street, ext_number, int_number,
        neighborhood, municipality, state, postal_code, phone, notes,
        latitude, longitude, leader_id, brigadist_id, created_by, status, created_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', NOW())`,
      [
        data.first_name, data.last_name_paternal, data.last_name_maternal || null,
        data.birth_date || null, data.sex || null, data.curp, data.elector_key,
        data.section_number, data.street, data.ext_number || null, data.int_number || null,
        data.neighborhood || null, "Emiliano Zapata", "Morelos", data.postal_code || null,
        data.phone || null, data.notes || null,
        lat, lng, leader_id, brigadist_id, created_by
      ]
    );

    return NextResponse.json({ 
      ok: true, 
      id: result.insertId, 
      message: "Militante creado con éxito" 
    });

  } catch (error: any) {
    console.error("DATABASE ERROR:", error);

    // --- DETECCIÓN DE CURP O CLAVE DUPLICADA (MySQL Error 1062) ---
    if (error.code === 'ER_DUP_ENTRY' || error.errno === 1062) {
      // Intentamos identificar qué campo falló para ser más precisos
      const msg = error.sqlMessage || "";
      let campoDuplicado = "La CURP o Clave de Elector";
      
      if (msg.includes('curp')) campoDuplicado = "La CURP";
      if (msg.includes('elector_key')) campoDuplicado = "La Clave de Elector";

      return NextResponse.json(
        { error: `${campoDuplicado} ya se encuentra registrada en el sistema.` },
        { status: 409 }
      );
    }

    return NextResponse.json(
      { error: "Error interno al procesar el registro territorial." }, 
      { status: 500 }
    );
  }
}