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

// =============================================================================
// POST /api/staff/virements-salaires/create
// Creates a new salary transfer record
// =============================================================================
export async function POST(req: NextRequest) {
  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, error: staffError } = 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 {
      org_id,
      period_month,
      period_label,
      deadline,
      mode,
      num_appel,
      total_net,
      notes,
    } = body;

    // 4) Validate required fields
    if (!org_id || !period_month || !deadline || !mode) {
      return NextResponse.json(
        {
          error: "Missing required fields: org_id, period_month, deadline, mode",
        },
        { status: 400 }
      );
    }

    // 5) Verify organization exists
    const { data: org, error: orgError } = await supabase
      .from("organizations")
      .select("id, name")
      .eq("id", org_id)
      .single();
    if (orgError || !org) {
      return NextResponse.json(
        { error: "Organization not found" },
        { status: 404 }
      );
    }

    // 6) Insert new salary transfer
    const insertData = {
      org_id,
      period_month,
      period_label: period_label || null,
      deadline,
      mode,
      num_appel: num_appel || null,
      total_net: total_net || null,
      notes: notes || null,
      notification_sent: false,
      notification_ok: false,
      salaires_payes: false,
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString(),
    };
    
    console.log("[create salary transfer] Insert data:", insertData);
    
    const { data: newTransfer, error: insertError } = await supabase
      .from("salary_transfers")
      .insert(insertData)
      .select()
      .single();

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

    // 7) Return the new record
    return NextResponse.json({
      success: true,
      data: newTransfer,
    });
  } catch (err: any) {
    console.error("Error in create salary transfer:", err);
    return NextResponse.json(
      { error: err.message || "Internal server error" },
      { status: 500 }
    );
  }
}
