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

export async function POST(req: NextRequest) {
  try {
    const supabase = createRouteHandlerClient({ cookies });
    
    // 1) Check auth
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    // 2) Check if staff
    const { data: me } = await supabase
      .from("staff_users")
      .select("is_staff")
      .eq("user_id", user.id)
      .maybeSingle();

    if (!me?.is_staff) {
      return NextResponse.json({ error: "Forbidden: staff only" }, { status: 403 });
    }

    // 3) Parse request body
    const body = await req.json();
    const { contractIds, analytique } = body;

    if (!contractIds || !Array.isArray(contractIds) || contractIds.length === 0) {
      return NextResponse.json(
        { error: "contractIds is required and must be a non-empty array" },
        { status: 400 }
      );
    }

    if (typeof analytique !== 'string' || !analytique.trim()) {
      return NextResponse.json(
        { error: "analytique is required and must be a non-empty string" },
        { status: 400 }
      );
    }

    const analytiqueValue = analytique.trim();

    // 4) Update contracts analytique (and production_name for compatibility)
    const { data: updatedContracts, error: updateError } = await supabase
      .from("cddu_contracts")
      .update({ 
        analytique: analytiqueValue,
        production_name: analytiqueValue // Mettre à jour aussi production_name pour compatibilité
      })
      .in("id", contractIds)
      .select("id, analytique");

    if (updateError) {
      console.error("Error updating contracts analytique:", updateError);
      return NextResponse.json(
        { error: "Failed to update contracts", details: updateError.message },
        { status: 500 }
      );
    }

    return NextResponse.json({
      success: true,
      count: updatedContracts?.length || 0,
      contracts: updatedContracts || [],
    });
  } catch (err: any) {
    console.error("Error in bulk-update-analytique:", err);
    return NextResponse.json(
      { error: err.message || "Internal server error" },
      { status: 500 }
    );
  }
}
