import { NextRequest, NextResponse } from "next/server";
import { createClient } from "@/lib/supabase/server";
import { createAdminClient } from "@/lib/supabase/admin";
import { InvoicePDF } from "@/components/invoice-pdf";
import { renderToBuffer } from "@react-pdf/renderer";
import React from "react";

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const inline = request.nextUrl.searchParams.get("inline") === "true";

    // 1. Auth check
    const supabase = await createClient();
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) {
      return new NextResponse("Unauthorized", { status: 401 });
    }

    const { data: dbUser } = await supabase
      .from("users")
      .select("role, company_id")
      .eq("id", user.id)
      .single();

    if (!dbUser) {
      return new NextResponse("Unauthorized", { status: 401 });
    }

    const adminDb = createAdminClient();

    // 2. Get the order from database
    const { data: order, error } = await adminDb
      .from("orders")
      .select("customer_data, order_data, total_price, created_at, pdf_url, order_number, company_id, user_id")
      .eq("id", id)
      .single();

    if (error || !order) {
      return new NextResponse("Order not found", { status: 404 });
    }

    // 3. Authorization: admin, owner, or company member
    const isAdmin = dbUser.role === "admin";
    const isOwner = order.user_id === user.id;
    const isCompanyMember = dbUser.company_id && order.company_id === dbUser.company_id;

    if (!isAdmin && !isOwner && !isCompanyMember) {
      return new NextResponse("Forbidden", { status: 403 });
    }

    const storageFileName = `ab_${id}.pdf`;
    let fileBuffer: Uint8Array | ArrayBuffer | null = null;

    // 4. Try to download from storage if pdf_url is set
    if (order.pdf_url) {
      try {
        const { data: fileData, error: downloadError } = await adminDb
          .storage
          .from("invoices")
          .download(storageFileName);

        if (!downloadError && fileData) {
          fileBuffer = await fileData.arrayBuffer();
        }
      } catch (storageErr) {
        console.warn("Could not retrieve file from storage, will regenerate:", storageErr);
      }
    }

    // 5. If file not found or pdf_url not set, generate dynamically
    if (!fileBuffer) {
      try {
        const formattedDate = new Date(order.created_at).toLocaleDateString('de-DE', {
          day: '2-digit',
          month: '2-digit',
          year: 'numeric',
        });

        const buffer = await renderToBuffer(
          React.createElement(InvoicePDF, {
            orderNumber: order.order_number || `AE-${id.slice(0, 8)}`,
            dateStr: formattedDate,
            customer: order.customer_data,
            orderData: order.order_data,
            totalPrice: Number(order.total_price),
          })
        );

        // Upload/Upsert to storage bucket
        const { error: uploadError } = await adminDb.storage
          .from("invoices")
          .upload(storageFileName, Buffer.from(buffer), {
            contentType: "application/pdf",
            upsert: true,
          });

        if (uploadError) {
          console.error("Failed to upload regenerated PDF:", uploadError);
        } else {
          await adminDb.from("orders").update({ pdf_url: storageFileName }).eq("id", id);
        }

        fileBuffer = buffer;
      } catch (genErr: any) {
        console.error("PDF generation failed inside API:", genErr);
        return new NextResponse("Error generating PDF: " + genErr.message, { status: 500 });
      }
    }

    // 6. Return as PDF response
    const downloadFileName = `Anfragebestaetigung_${order.order_number || id.slice(0, 8)}.pdf`;
    
    const headers = new Headers();
    headers.append("Content-Type", "application/pdf");
    headers.append("Cache-Control", "private, no-cache");
    if (inline) {
      headers.append("Content-Disposition", `inline; filename="${downloadFileName}"`);
    } else {
      headers.append("Content-Disposition", `attachment; filename="${downloadFileName}"`);
    }

    return new NextResponse(fileBuffer as any, {
      status: 200,
      headers,
    });
  } catch (err: any) {
    console.error("Download endpoint failed:", err);
    return new NextResponse(err.message || "Internal Server Error", { status: 500 });
  }
}
