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

export async function POST(req: Request) {
  try {
    const body = await req.json();
    const { full_name, email, password, role, phone, militant_id } = body;

    // 1. Obtener Token y validar existencia (Solución error TS2345)
    const cookieStore = await cookies();
    const token = cookieStore.get("token")?.value;

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

    // Pasamos el token asegurando que es string
    const decoded: any = verifyToken(token);
    if (!decoded) {
      return NextResponse.json({ error: "Token inválido" }, { status: 401 });
    }

    // 2. Seguridad: Hasheo
    const salt = await bcrypt.genSalt(10);
    const password_hash = await bcrypt.hash(password, salt);

    // 3. Inserción con Vínculos (Usa leader_id de la sesión)
    await db.query(
      `INSERT INTO users (full_name, email, password_hash, role, phone, is_active, created_at, militant_id, leader_id) 
       VALUES (?, ?, ?, ?, ?, 1, NOW(), ?, ?)`,
      [full_name, email, password_hash, role, phone, militant_id, decoded.id]
    );

    return NextResponse.json({ ok: true });
  } catch (error: any) {
    console.error("CREATE_USER_ERROR:", error);
    return NextResponse.json({ error: "Email ya registrado o error de conexión" }, { status: 400 });
  }
}