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

// =============================================================================
// PATCH /api/staff/virements-salaires/[id]/route.ts
// Updates a salary transfer record
// =============================================================================
export async function PATCH(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    // 1) Check auth
    const supabase = createRouteHandlerClient({ cookies });
    const {
      data: { session },
      error: sessionError,
    } = await supabase.auth.getSession();
    
    if (sessionError || !session) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    
    const user = session.user;

    // 2) Check if staff
    const { data: staffData } = await supabase
      .from("staff_users")
      .select("is_staff")
      .eq("user_id", user.id)
      .maybeSingle();
      
    const isStaff = staffData?.is_staff || false;
    
    if (!isStaff) {
      return NextResponse.json(
        { error: "Forbidden: staff only" },
        { status: 403 }
      );
    }

    // 3) Parse request body
    const body = await req.json();
    const {
      period_month,
      period_label,
      deadline,
      mode,
      num_appel,
      total_net,
      notes,
      client_wire_received_at,
      notification_ok,
      salaires_payes,
    } = body;

    // 4) Build update object (only include provided fields)
    const updateData: any = {
      updated_at: new Date().toISOString(),
    };
    
    if (period_month !== undefined) updateData.period_month = period_month;
    if (period_label !== undefined) updateData.period_label = period_label;
    if (deadline !== undefined) updateData.deadline = deadline;
    if (mode !== undefined) updateData.mode = mode;
    if (num_appel !== undefined) updateData.num_appel = num_appel;
    if (total_net !== undefined) updateData.total_net = total_net;
    if (notes !== undefined) updateData.notes = notes;
    if (client_wire_received_at !== undefined) updateData.client_wire_received_at = client_wire_received_at;
    if (notification_ok !== undefined) updateData.notification_ok = notification_ok;
    if (salaires_payes !== undefined) updateData.salaires_payes = salaires_payes;

    console.log("[update salary transfer] Update data:", updateData);

    // 5) Update the record
    const { data: updatedTransfer, error: updateError } = await supabase
      .from("salary_transfers")
      .update(updateData)
      .eq("id", params.id)
      .select()
      .single();

    if (updateError) {
      console.error("[update salary transfer] Update error:", updateError);
      return NextResponse.json(
        { 
          error: "Failed to update salary transfer", 
          details: updateError.message,
          code: updateError.code,
          hint: updateError.hint 
        },
        { status: 500 }
      );
    }

    // 6) Return the updated record
    return NextResponse.json({
      success: true,
      data: updatedTransfer,
    });
  } catch (err: any) {
    console.error("[update salary transfer] Error:", err);
    return NextResponse.json(
      { error: err.message || "Internal server error" },
      { status: 500 }
    );
  }
}

// =============================================================================
// DELETE /api/staff/virements-salaires/[id]/route.ts
// Deletes a salary transfer record
// =============================================================================
export async function DELETE(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    // 1) Check auth
    const supabase = createRouteHandlerClient({ cookies });
    const {
      data: { session },
      error: sessionError,
    } = await supabase.auth.getSession();
    
    if (sessionError || !session) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    
    const user = session.user;

    // 2) Check if staff
    const { data: staffData } = await supabase
      .from("staff_users")
      .select("is_staff")
      .eq("user_id", user.id)
      .maybeSingle();
      
    const isStaff = staffData?.is_staff || false;
    
    if (!isStaff) {
      return NextResponse.json(
        { error: "Forbidden: staff only" },
        { status: 403 }
      );
    }

    // 3) Get the record first (to get the PDF URL if needed)
    const { data: transfer, error: fetchError } = await supabase
      .from("salary_transfers")
      .select("*")
      .eq("id", params.id)
      .single();

    if (fetchError || !transfer) {
      return NextResponse.json(
        { error: "Salary transfer not found" },
        { status: 404 }
      );
    }

    console.log("[delete salary transfer] Deleting:", params.id, transfer.callsheet_url);

    // 4) Delete the record
    const { error: deleteError } = await supabase
      .from("salary_transfers")
      .delete()
      .eq("id", params.id);

    if (deleteError) {
      console.error("[delete salary transfer] Delete error:", deleteError);
      return NextResponse.json(
        { 
          error: "Failed to delete salary transfer", 
          details: deleteError.message,
          code: deleteError.code,
          hint: deleteError.hint 
        },
        { status: 500 }
      );
    }

    // Note: We don't delete the S3 file here to keep a backup
    // If you want to delete it, you'd need to parse the URL and use S3 DeleteObjectCommand

    // 5) Return success
    return NextResponse.json({
      success: true,
      message: "Salary transfer deleted successfully",
    });
  } catch (err: any) {
    console.error("[delete salary transfer] Error:", err);
    return NextResponse.json(
      { error: err.message || "Internal server error" },
      { status: 500 }
    );
  }
}
