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

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

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

    // Traemos las campañas asignadas incluyendo las instrucciones que dejó el Líder
    const [rows]: any = await db.query(`
      SELECT 
        c.id,
        c.title,
        c.message_text,
        c.image_url_1,
        c.image_url_2,
        c.image_url_3,
        c.created_at,
        t.is_read, 
        t.is_disseminated,
        t.leader_instructions -- <--- IMPORTANTE: Pedimos la columna de instrucciones
      FROM digital_campaigns c
      INNER JOIN campaign_tracking t ON c.id = t.campaign_id
      WHERE t.user_id = ?
      ORDER BY c.created_at DESC
    `, [decoded.id]);

    // Marcado automático de lectura: Si el brigadista entró al dashboard, las ve todas.
    if (rows.length > 0) {
      await db.query(
        "UPDATE campaign_tracking SET is_read = 1, read_at = NOW() WHERE user_id = ? AND is_read = 0",
        [decoded.id]
      );
    }

    return NextResponse.json(rows);
  } catch (error) {
    console.error("BRIGADIST_GET_ERROR:", error);
    return NextResponse.json({ error: "Error de servidor al cargar misiones" }, { status: 500 });
  }
}