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

export async function POST(req: Request) {
  try {
    const { id, status } = await req.json(); // id del militante y nuevo status ('inactive')
    
    const cookieStore = await cookies();
    const token = cookieStore.get("token")?.value;
    const decoded: any = verifyToken(token || "");

    // Solo Admin y Leader pueden dar de baja registros
    if (!decoded || (decoded.role !== 'admin' && decoded.role !== 'leader')) {
      return NextResponse.json({ error: "No autorizado" }, { status: 403 });
    }

    // 1. Cambiamos el estatus en la tabla MILITANTS
    await db.query(
      "UPDATE militants SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
      [status, id]
    );

    // 2. SEGURIDAD: Si este militante es también un USUARIO del sistema, 
    // lo bloqueamos para que no pueda volver a loguearse (active = 0)
    if (status === 'inactive') {
      await db.query(
        "UPDATE users SET active = 0 WHERE militant_id = ?",
        [id]
      );
    }

    return NextResponse.json({ success: true, message: "Estatus actualizado correctamente" });

  } catch (error: any) {
    console.error("TOGGLE_STATUS_ERROR:", error);
    return NextResponse.json({ error: "Error al procesar la baja" }, { status: 500 });
  }
}