// 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";

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 });
    }

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

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

    // Vérifier que l'utilisateur a accès à cette organisation
    let hasAccess = false;
    
    // Vérification staff
    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 {}

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

    if (!hasAccess) {
      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 });
  }
}