import { NextResponse, type NextRequest } from "next/server";
import { getCurrentProfile } from "@/lib/auth";
import { createAdminSupabaseClient } from "@/lib/supabase/admin";
import { readPrivateUpload, type UploadKind } from "@/lib/storage";
import { writeAuditLog } from "@/lib/audit";
import type { OrphanUploadIdentity } from "@/lib/orphan-upload-path";

export const dynamic = "force-dynamic";

export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const profile = await getCurrentProfile();
  if (!profile || !profile.is_active) return NextResponse.json({ message: "غير مصرح" }, { status: 401 });

  const { id } = await params;
  const supabase = createAdminSupabaseClient();
  const { data: file } = await supabase
    .from("file_assets")
    .select("id, stored_name, original_name, extension, mime_type")
    .eq("id", id)
    .maybeSingle();

  if (!file) return NextResponse.json({ message: "الملف غير موجود" }, { status: 404 });
  const [{ data: orphanDocument }, { data: receipt }] = await Promise.all([
    supabase
      .from("orphan_documents")
      .select("orphan_id")
      .eq("file_id", id)
      .maybeSingle(),
    supabase
      .from("transfer_receipts")
      .select("orphan_transfers(orphan_id,orphan_transfer_sponsors(sponsor_id))")
      .eq("file_id", id)
      .maybeSingle()
  ]);

  let entityId: string | null = null;
  let kind: UploadKind | null = null;
  let receiptSponsorIds: string[] = [];

  if (orphanDocument) {
    entityId = orphanDocument.orphan_id;
    kind = "documents";
  } else {
    const transferValue = receipt?.orphan_transfers as
      | { orphan_id: string; orphan_transfer_sponsors: { sponsor_id: string } | { sponsor_id: string }[] | null }
      | { orphan_id: string; orphan_transfer_sponsors: { sponsor_id: string } | { sponsor_id: string }[] | null }[]
      | null;
    const transfer = Array.isArray(transferValue) ? transferValue[0] : transferValue;
    if (transfer) {
      entityId = transfer.orphan_id;
      const sponsorLinks = Array.isArray(transfer.orphan_transfer_sponsors)
        ? transfer.orphan_transfer_sponsors
        : transfer.orphan_transfer_sponsors
          ? [transfer.orphan_transfer_sponsors]
          : [];
      receiptSponsorIds = sponsorLinks.map((link) => link.sponsor_id);
      kind = "receipts";
    }
  }

  let allowed = profile.role === "admin" && Boolean(entityId && kind);
  if (profile.role !== "admin" && entityId && kind) {
    if (kind === "documents") {
      const { data: sponsorship } = await supabase
        .from("sponsorships")
        .select("id")
        .eq("donor_id", profile.id)
        .eq("orphan_id", entityId)
        .eq("status", "active")
        .maybeSingle();
      allowed = Boolean(sponsorship);
    } else {
      allowed = receiptSponsorIds.includes(profile.id);
    }
  }

  await writeAuditLog({
    actorId: profile.id,
    action: allowed ? "file.viewed" : "file.access_denied",
    entityType: "file_asset",
    entityId: id,
    metadata: { linkedOrphanId: entityId, uploadKind: kind }
  });
  if (!allowed) return NextResponse.json({ message: "غير مصرح بعرض هذا الملف" }, { status: 403 });

  const { data: orphan } = await supabase
    .from("orphans")
    .select("id,full_name,case_number")
    .eq("id", entityId!)
    .maybeSingle();
  if (!orphan) return NextResponse.json({ message: "ملف اليتيم غير موجود" }, { status: 404 });
  const uploadIdentity: OrphanUploadIdentity = {
    orphanId: orphan.id,
    orphanName: orphan.full_name,
    caseNumber: orphan.case_number
  };

  try {
    const content = await readPrivateUpload(uploadIdentity, kind!, file.stored_name, file.extension);
    const disposition = request.nextUrl.searchParams.get("download") === "1" ? "attachment" : "inline";
    const encodedName = encodeURIComponent(file.original_name);
    return new NextResponse(Uint8Array.from(content), {
      headers: {
        "Content-Type": file.mime_type,
        "Content-Length": String(content.length),
        "Content-Disposition": `${disposition}; filename*=UTF-8''${encodedName}`,
        "Cache-Control": "private, no-store, max-age=0",
        "X-Content-Type-Options": "nosniff"
      }
    });
  } catch {
    return NextResponse.json({ message: "تعذر قراءة الملف" }, { status: 404 });
  }
}
