export const dynamic = 'force-dynamic';
export const revalidate = 0;
export const runtime = 'nodejs';

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

// GET - Récupérer uniquement les informations de statut pour le header
export async function GET() {
  try {
    const sb = createSbServer();
    
    const { data, error } = await sb
      .from("maintenance_status")
      .select("status_top_text, status_middle_text, status_bottom_text, status_top_color, status_middle_color, status_bottom_color, status_top_description, status_middle_description, status_bottom_description")
      .single();
    
    if (error) {
      console.error("Error fetching status info:", error);
      return NextResponse.json({ error: "Failed to fetch status info" }, { status: 500 });
    }
    
    return NextResponse.json(data);
  } catch (error) {
    console.error("Unexpected error:", error);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}

// PUT - Mettre à jour les textes et couleurs des voyants (staff uniquement)
export async function PUT(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 { 
      status_top_text,
      status_middle_text, 
      status_bottom_text, 
      status_top_color,
      status_middle_color, 
      status_bottom_color,
      status_top_description,
      status_middle_description,
      status_bottom_description
    } = body;
    
    // Validation des couleurs autorisées
    const allowedColors = ['emerald', 'red', 'yellow', 'orange', 'sky', 'blue', 'purple', 'pink', 'gray'];
    
    if (status_top_color && !allowedColors.includes(status_top_color)) {
      return NextResponse.json({ 
        error: `Invalid top color. Allowed colors: ${allowedColors.join(', ')}` 
      }, { status: 400 });
    }

    if (status_middle_color && !allowedColors.includes(status_middle_color)) {
      return NextResponse.json({ 
        error: `Invalid middle color. Allowed colors: ${allowedColors.join(', ')}` 
      }, { status: 400 });
    }
    
    if (status_bottom_color && !allowedColors.includes(status_bottom_color)) {
      return NextResponse.json({ 
        error: `Invalid bottom color. Allowed colors: ${allowedColors.join(', ')}` 
      }, { status: 400 });
    }
    
    // Validation des textes
    if (status_top_text && (typeof status_top_text !== 'string' || status_top_text.length > 200)) {
      return NextResponse.json({ 
        error: "Top text must be a string with max 200 characters" 
      }, { status: 400 });
    }

    if (status_middle_text && (typeof status_middle_text !== 'string' || status_middle_text.length > 200)) {
      return NextResponse.json({ 
        error: "Middle text must be a string with max 200 characters" 
      }, { status: 400 });
    }
    
    if (status_bottom_text && (typeof status_bottom_text !== 'string' || status_bottom_text.length > 200)) {
      return NextResponse.json({ 
        error: "Bottom text must be a string with max 200 characters" 
      }, { status: 400 });
    }

    // Validation des descriptions (max 1000 caractères)
    if (status_top_description && (typeof status_top_description !== 'string' || status_top_description.length > 1000)) {
      return NextResponse.json({ 
        error: "Top description must be a string with max 1000 characters" 
      }, { status: 400 });
    }

    if (status_middle_description && (typeof status_middle_description !== 'string' || status_middle_description.length > 1000)) {
      return NextResponse.json({ 
        error: "Middle description must be a string with max 1000 characters" 
      }, { status: 400 });
    }

    if (status_bottom_description && (typeof status_bottom_description !== 'string' || status_bottom_description.length > 1000)) {
      return NextResponse.json({ 
        error: "Bottom description must be a string with max 1000 characters" 
      }, { status: 400 });
    }
    
    // Construire l'objet de mise à jour (seulement les champs fournis)
    const updateData: any = {
      updated_by_staff_id: user.id
    };
    
    if (status_top_text !== undefined) updateData.status_top_text = status_top_text;
    if (status_middle_text !== undefined) updateData.status_middle_text = status_middle_text;
    if (status_bottom_text !== undefined) updateData.status_bottom_text = status_bottom_text;
    if (status_top_color !== undefined) updateData.status_top_color = status_top_color;
    if (status_middle_color !== undefined) updateData.status_middle_color = status_middle_color;
    if (status_bottom_color !== undefined) updateData.status_bottom_color = status_bottom_color;
    if (status_top_description !== undefined) updateData.status_top_description = status_top_description;
    if (status_middle_description !== undefined) updateData.status_middle_description = status_middle_description;
    if (status_bottom_description !== undefined) updateData.status_bottom_description = status_bottom_description;
    
    // Mettre à jour les informations de statut
    const { data, error } = await sb
      .from("maintenance_status")
      .update(updateData)
      .eq("id", 1)
      .select("status_top_text, status_middle_text, status_bottom_text, status_top_color, status_middle_color, status_bottom_color, status_top_description, status_middle_description, status_bottom_description, updated_at, updated_by_staff_id")
      .single();
    
    if (error) {
      console.error("Error updating status info:", error);
      return NextResponse.json({ error: "Failed to update status info" }, { status: 500 });
    }
    
    return NextResponse.json(data);
  } catch (error) {
    console.error("Unexpected error:", error);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}