// app/api/salary-transfer-pdf/[id]/route.ts
import { NextRequest, NextResponse } from "next/server";
import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
import { cookies } from "next/headers";
import { createSbServiceRole } from "@/lib/supabaseServer";

export async function GET(req: NextRequest, { params }: { params: { id: string } }) {
  try {
    const { id } = params;
    
    if (!id) {
      return new NextResponse("ID required", { status: 400 });
    }

  const sb = createRouteHandlerClient({ cookies });
  const { data: { user }, error: userError } = await sb.auth.getUser();
    
    if (!user) {
      console.error("[salary-transfer-pdf][auth] No authenticated user");
      return new NextResponse("Unauthorized", { status: 401 });
    }

    // Use a service-role client to reliably read salary_transfers and membership
    const service = createSbServiceRole();

    // Récupérer les détails du virement de salaire (service role to avoid RLS surprises)
    const { data: salaryTransfer, error } = await service
      .from("salary_transfers")
      .select("callsheet_url, org_id")
      .eq("id", id)
      .maybeSingle();

    if (error || !salaryTransfer) {
      console.error("[salary-transfer-pdf][db] Error fetching salary transfer:", error);
      return new NextResponse("Salary transfer not found", { status: 404 });
    }

    console.log("[salary-transfer-pdf] salaryTransfer:", { id, org_id: salaryTransfer.org_id });

    // Vérifier que l'utilisateur a accès à cette organisation
    let hasAccess = false;

    // Vérification staff (can use sb - but we'll also check via service for clarity)
    try {
      const { data: staffData } = await sb
        .from("staff_users")
        .select("is_staff")
        .eq("user_id", user.id)
        .maybeSingle();
      if (staffData?.is_staff) {
        hasAccess = true;
      }
    } catch (e) {
      console.warn("[salary-transfer-pdf] staff check failed:", (e as any)?.message || e);
    }

    // Si pas staff, vérifier l'appartenance à l'organisation en lecture via service role
    if (!hasAccess) {
      try {
        const { data: memberData, error: memberErr } = await service
          .from("organization_members")
          .select("organization_id, revoked, user_id")
          .eq("user_id", user.id)
          .eq("organization_id", salaryTransfer.org_id)
          .maybeSingle();

        if (memberErr) {
          console.warn("[salary-transfer-pdf] membership lookup error:", memberErr);
        }

        console.log("[salary-transfer-pdf] membership lookup:", { memberData });
        hasAccess = !!memberData && memberData.revoked !== true;
      } catch (e) {
        console.warn("[salary-transfer-pdf] membership check failed:", (e as any)?.message || e);
      }
    }

    if (!hasAccess) {
      console.error("[salary-transfer-pdf] Access denied", { userId: user.id, orgId: salaryTransfer.org_id });
      return new NextResponse("Access denied", { status: 403 });
    }

    // Si callsheet_url est un URL complet, rediriger vers ce URL
    if (salaryTransfer.callsheet_url) {
      if (salaryTransfer.callsheet_url.startsWith('http')) {
        return NextResponse.redirect(salaryTransfer.callsheet_url);
      }
      
      // Si c'est juste un identifiant, construire l'URL vers le système de fichiers
      // (à adapter selon votre système de stockage)
      const fileUrl = `${process.env.DOCUMENTS_BASE_URL}/salary-transfers/${salaryTransfer.callsheet_url}.pdf`;
      return NextResponse.redirect(fileUrl);
    }

    return new NextResponse("PDF not available", { status: 404 });

  } catch (e: any) {
    console.error("[salary-transfer-pdf][exception]", e?.message);
    return new NextResponse("Server error", { status: 500 });
  }
}