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

// =============================================================================
// GET /api/staff/payslips/available?org_id=xxx
// Récupère les paies disponibles pour une organisation (non liées à un virement manuel)
// =============================================================================
export async function GET(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) Get org_id from query params
    const searchParams = req.nextUrl.searchParams;
    const orgId = searchParams.get("org_id");
    
    if (!orgId) {
      return NextResponse.json(
        { error: "Missing org_id parameter" },
        { status: 400 }
      );
    }

    // 4) Get payslips for this organization (last 2 months by default)
    const twoMonthsAgo = new Date();
    twoMonthsAgo.setMonth(twoMonthsAgo.getMonth() - 2);
    const minDate = twoMonthsAgo.toISOString().split('T')[0]; // Format YYYY-MM-DD
    
    const { data: payslips, error: payslipsError } = await supabase
      .from("payslips")
      .select(`
        id,
        contract_id,
        period_month,
        period_start,
        period_end,
        pay_date,
        net_amount,
        net_after_withholding,
        processed,
        organization_id,
        cddu_contracts (
          id,
          contract_number,
          employee_name,
          employee_id,
          employee_matricule,
          salaries (
            nom,
            prenom
          )
        )
      `)
      .eq("organization_id", orgId)
      .gte("period_start", minDate)
      .order("period_start", { ascending: false });

    if (payslipsError) {
      console.error("[GET /api/staff/payslips/available] Error:", payslipsError);
      return NextResponse.json(
        { error: "Failed to fetch payslips", details: payslipsError.message },
        { status: 500 }
      );
    }

    // 5) Get payslips already linked to manual transfers
    const { data: linkedPayslips, error: linkedError } = await supabase
      .from("salary_transfer_payslips")
      .select("payslip_id");

    if (linkedError) {
      console.warn("[GET /api/staff/payslips/available] Warning: could not fetch linked payslips:", linkedError);
      // Continue without filtering
      return NextResponse.json({
        success: true,
        payslips: payslips || [],
        total: payslips?.length || 0,
      });
    }

    // 6) Filter out already linked payslips
    const linkedIds = new Set(linkedPayslips?.map(lp => lp.payslip_id) || []);
    const availablePayslips = (payslips || []).filter(p => !linkedIds.has(p.id));

    console.log("[GET /api/staff/payslips/available] Results:", {
      orgId,
      total: payslips?.length || 0,
      linked: linkedIds.size,
      available: availablePayslips.length,
    });

    return NextResponse.json({
      success: true,
      payslips: availablePayslips,
      total: availablePayslips.length,
      stats: {
        total: payslips?.length || 0,
        linked: linkedIds.size,
        available: availablePayslips.length,
      },
    });
  } catch (err: any) {
    console.error("[GET /api/staff/payslips/available] Error:", err);
    return NextResponse.json(
      { error: err.message || "Internal server error" },
      { status: 500 }
    );
  }
}
