import Link from "next/link";
import { notFound } from "next/navigation";
import { requireUser } from "@/lib/auth/session";
import { createClient } from "@/lib/supabase/server";
import { Button } from "@/components/ui/button";
import type { ApplicationDocument } from "@/lib/types";
import {
  PartnerDocumentsClient,
  type DocumentWithUrl,
} from "./documents-client";

export default async function PartnerDocumentsPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const user = await requireUser();
  const supabase = await createClient();

  const { data: application } = await supabase
    .from("student_applications")
    .select("applicant_name")
    .eq("id", id)
    .eq("partner_id", user.id)
    .single();

  if (!application) notFound();

  const { data: docs } = await supabase
    .from("application_documents")
    .select("*")
    .eq("student_application_id", id)
    .order("created_at", { ascending: false });

  const documents = (docs ?? []) as ApplicationDocument[];
  const docsWithUrls: DocumentWithUrl[] = await Promise.all(
    documents.map(async (doc) => {
      const { data } = await supabase.storage
        .from("documents")
        .createSignedUrl(doc.file_path, 3600);
      return { ...doc, signedUrl: data?.signedUrl ?? null };
    }),
  );

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="font-heading text-2xl font-bold text-brand-navy">
            Documents — {application.applicant_name}
          </h1>
        </div>
        <Button asChild variant="outline">
          <Link href={`/partner/applications/${id}`}>Back to application</Link>
        </Button>
      </div>
      <PartnerDocumentsClient applicationId={id} documents={docsWithUrls} />
    </div>
  );
}
