// app/api/maintenance/route.ts
import { createSbServer } from "@/lib/supabaseServer";
import { NextResponse } from "next/server";

// GET - Récupérer le statut de maintenance
export async function GET() {
  try {
    const sb = createSbServer();
    
    const { data, error } = await sb
      .from("maintenance_status")
      .select("*")
      .single();
    
    if (error) {
      console.error("Error fetching maintenance status:", error);
      return NextResponse.json({ error: "Failed to fetch maintenance status" }, { status: 500 });
    }
    
    return NextResponse.json(data);
  } catch (error) {
    console.error("Unexpected error:", error);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}

// POST - Activer/désactiver la maintenance (staff uniquement)
export async function POST(request: Request) {
  try {
    const sb = createSbServer();
    
    // Vérifier l'authentification
    const { data: { user } } = await sb.auth.getUser();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    
    // Vérifier si l'utilisateur est staff
    const { data: staffData } = await sb
      .from("staff_users")
      .select("is_staff")
      .eq("user_id", user.id)
      .single();
    
    if (!staffData?.is_staff) {
      return NextResponse.json({ error: "Forbidden - Staff only" }, { status: 403 });
    }
    
    // Récupérer les données de la requête
    const body = await request.json();
    const { is_maintenance_mode, maintenance_message, scheduled_end_date } = body;
    
    // Validation
    if (typeof is_maintenance_mode !== "boolean") {
      return NextResponse.json({ error: "is_maintenance_mode must be boolean" }, { status: 400 });
    }
    
    // Mettre à jour le statut de maintenance
    const { data, error } = await sb
      .from("maintenance_status")
      .update({
        is_maintenance_mode,
        maintenance_message: is_maintenance_mode ? maintenance_message : null,
        scheduled_end_date: is_maintenance_mode ? scheduled_end_date : null,
        created_by_staff_id: user.id
      })
      .eq("id", 1)
      .select()
      .single();
    
    if (error) {
      console.error("Error updating maintenance status:", error);
      return NextResponse.json({ error: "Failed to update maintenance status" }, { status: 500 });
    }
    
    return NextResponse.json(data);
  } catch (error) {
    console.error("Unexpected error:", error);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}