import { NextResponse } from "next/server";
import { db } from "@/lib/db";
import { cookies } from "next/headers";
import { verifyToken } from "@/lib/auth";
import { writeFile, mkdir } from "fs/promises";
import path from "path";

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

    if (!decoded || decoded.role !== 'admin') {
      return NextResponse.json({ error: "No autorizado" }, { status: 401 });
    }

    const formData = await req.formData();
    const title = formData.get("title");
    const message_text = formData.get("message_text");
    const instructions = formData.get("instructions"); // <--- CAPTURAMOS LAS INSTRUCCIONES
    const scope = formData.get("scope");
    const neighborhoodsRaw = formData.get("neighborhoods");
    const neighborhoods = neighborhoodsRaw ? JSON.parse(neighborhoodsRaw as string) : [];
    const images = formData.getAll("images") as File[];

    // 1. Manejo de imágenes
    const savedImagePaths: (string | null)[] = [null, null, null];
    const uploadDir = path.join(process.cwd(), "public/uploads/campaigns");

    try { await mkdir(uploadDir, { recursive: true }); } catch (e) {}

    for (let i = 0; i < images.length && i < 3; i++) {
      const file = images[i];
      if (file && file.size > 0) {
        const bytes = await file.arrayBuffer();
        const buffer = Buffer.from(bytes);
        const cleanFileName = `${Date.now()}_${file.name.replace(/\s+/g, "_")}`;
        await writeFile(path.join(uploadDir, cleanFileName), buffer);
        savedImagePaths[i] = `/uploads/campaigns/${cleanFileName}`;
      }
    }

    // 2. Insertar Campaña incluyendo el nuevo campo INSTRUCTIONS
    const [result]: any = await db.query(
      "INSERT INTO digital_campaigns (admin_id, title, message_text, instructions, image_url_1, image_url_2, image_url_3, scope) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
      [decoded.id, title, message_text, instructions, savedImagePaths[0], savedImagePaths[1], savedImagePaths[2], scope]
    );
    const campaignId = result.insertId;

    // 3. Lógica de Filtrado: Usando militant_id para segmentar por territorio
    let query = `
      SELECT u.id 
      FROM users u
      INNER JOIN militants m ON u.militant_id = m.id
      WHERE u.role IN ('leader', 'brigadist') AND u.active = 1
    `;
    let params: any[] = [];

    if (neighborhoods.length > 0) {
      query += " AND m.neighborhood IN (?)";
      params.push(neighborhoods);
    }

    const [leaders]: any = await db.query(query, params);

    // 4. Vincular la campaña en campaign_traking (Nombre corregido)
    if (leaders.length > 0) {
      const trackingData = leaders.map((l: any) => [campaignId, l.id]);
      await db.query(
        "INSERT INTO campaign_tracking (campaign_id, user_id) VALUES ?", 
        [trackingData]
      );
    }

    return NextResponse.json({ ok: true, campaignId });
  } catch (error) {
    console.error("CAMPAIGN_POST_ERROR:", error);
    return NextResponse.json({ error: "Error al procesar el despliegue digital" }, { status: 500 });
  }
}