import { NextResponse } from "next/server";
import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
import { cookies } from "next/headers";

export const dynamic = "force-dynamic";

// GET: Récupérer toutes les bannières (staff) ou la bannière active (public)
export async function GET() {
  const sb = createRouteHandlerClient({ cookies });
  
  const { data: { user } } = await sb.auth.getUser();
  
  // Vérifier si l'utilisateur est staff
  let isStaff = false;
  if (user) {
    const { data: staffData } = await sb
      .from("staff_users")
      .select("is_staff")
      .eq("user_id", user.id)
      .maybeSingle();
    isStaff = !!staffData?.is_staff;
  }
  
  if (isStaff) {
    // Staff : récupérer toutes les bannières
    const { data, error } = await sb
      .from("promo_banners")
      .select("*")
      .order("created_at", { ascending: false });
    
    if (error) {
      return NextResponse.json({ error: error.message }, { status: 500 });
    }
    
    return NextResponse.json({ banners: data });
  } else {
    // Public : récupérer uniquement la bannière active
    const { data, error } = await sb
      .from("promo_banners")
      .select("*")
      .eq("is_active", true)
      .maybeSingle();
    
    if (error && error.code !== "PGRST116") {
      return NextResponse.json({ error: error.message }, { status: 500 });
    }
    
    return NextResponse.json({ banner: data });
  }
}

// POST: Créer une nouvelle bannière (staff uniquement)
export async function POST(req: Request) {
  const sb = createRouteHandlerClient({ cookies });
  
  const { data: { user } } = await sb.auth.getUser();
  if (!user) {
    return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
  }
  
  // Vérifier que l'utilisateur est staff
  const { data: staffData } = await sb
    .from("staff_users")
    .select("is_staff")
    .eq("user_id", user.id)
    .maybeSingle();
  
  if (!staffData?.is_staff) {
    return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
  }
  
  try {
    const body = await req.json();
    const {
      text,
      cta_text,
      cta_link,
      countdown_enabled,
      countdown_end_date,
      gradient_from,
      gradient_to,
      text_color,
      cta_bg_color,
      cta_text_color,
      is_active,
    } = body;
    
    if (!text) {
      return NextResponse.json({ error: "Le texte est requis" }, { status: 400 });
    }
    
    // Si on active cette bannière, désactiver toutes les autres
    if (is_active) {
      await sb
        .from("promo_banners")
        .update({ is_active: false })
        .neq("id", "00000000-0000-0000-0000-000000000000"); // Désactive toutes
    }
    
    const { data, error } = await sb
      .from("promo_banners")
      .insert({
        text,
        cta_text: cta_text || null,
        cta_link: cta_link || null,
        countdown_enabled: countdown_enabled || false,
        countdown_end_date: countdown_end_date || null,
        gradient_from: gradient_from || "indigo-600",
        gradient_to: gradient_to || "purple-600",
        text_color: text_color || "slate-800",
        cta_bg_color: cta_bg_color || "#efc543",
        cta_text_color: cta_text_color || "slate-900",
        is_active: is_active || false,
        created_by: user.id,
        updated_by: user.id,
      })
      .select()
      .single();
    
    if (error) {
      return NextResponse.json({ error: error.message }, { status: 500 });
    }
    
    return NextResponse.json({ banner: data });
  } catch (err) {
    return NextResponse.json({ error: "Erreur lors de la création" }, { status: 500 });
  }
}

// PATCH: Mettre à jour une bannière existante (staff uniquement)
export async function PATCH(req: Request) {
  const sb = createRouteHandlerClient({ cookies });
  
  const { data: { user } } = await sb.auth.getUser();
  if (!user) {
    return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
  }
  
  // Vérifier que l'utilisateur est staff
  const { data: staffData } = await sb
    .from("staff_users")
    .select("is_staff")
    .eq("user_id", user.id)
    .maybeSingle();
  
  if (!staffData?.is_staff) {
    return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
  }
  
  try {
    const body = await req.json();
    const { id, ...updates } = body;
    
    if (!id) {
      return NextResponse.json({ error: "L'ID est requis" }, { status: 400 });
    }
    
    // Si on active cette bannière, désactiver toutes les autres
    if (updates.is_active === true) {
      await sb
        .from("promo_banners")
        .update({ is_active: false })
        .neq("id", id);
    }
    
    const { data, error } = await sb
      .from("promo_banners")
      .update({
        ...updates,
        updated_by: user.id,
      })
      .eq("id", id)
      .select()
      .single();
    
    if (error) {
      return NextResponse.json({ error: error.message }, { status: 500 });
    }
    
    return NextResponse.json({ banner: data });
  } catch (err) {
    return NextResponse.json({ error: "Erreur lors de la mise à jour" }, { status: 500 });
  }
}

// DELETE: Supprimer une bannière (staff uniquement)
export async function DELETE(req: Request) {
  const sb = createRouteHandlerClient({ cookies });
  
  const { data: { user } } = await sb.auth.getUser();
  if (!user) {
    return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
  }
  
  // Vérifier que l'utilisateur est staff
  const { data: staffData } = await sb
    .from("staff_users")
    .select("is_staff")
    .eq("user_id", user.id)
    .maybeSingle();
  
  if (!staffData?.is_staff) {
    return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
  }
  
  try {
    const { searchParams } = new URL(req.url);
    const id = searchParams.get("id");
    
    if (!id) {
      return NextResponse.json({ error: "L'ID est requis" }, { status: 400 });
    }
    
    const { error } = await sb
      .from("promo_banners")
      .delete()
      .eq("id", id);
    
    if (error) {
      return NextResponse.json({ error: error.message }, { status: 500 });
    }
    
    return NextResponse.json({ success: true });
  } catch (err) {
    return NextResponse.json({ error: "Erreur lors de la suppression" }, { status: 500 });
  }
}
