import { auth } from "@/auth";
import { db } from "@/lib/db";
import { notFound, redirect } from "next/navigation";
import { ReceiptForm } from "./receipt-form";
import type { Metadata } from "next";

export const metadata: Metadata = { title: "Confirm Receipt" };

interface Props {
  params: Promise<{ id: string }>;
}

export default async function ReceiptPage({ params }: Props) {
  const session = await auth();
  if (!session?.user) redirect("/login");

  const { id } = await params;

  const po = await db.purchaseOrder.findUnique({
    where: { id },
    select: { id: true, poNumber: true, title: true, status: true, submitterId: true },
  });

  if (!po) notFound();
  if (po.status !== "PAID_DELIVERED") redirect(`/po/${id}`);
  if (po.submitterId !== session.user.id && session.user.role !== "SUPERUSER") {
    redirect(`/po/${id}`);
  }

  return (
    <div className="max-w-lg">
      <div className="mb-6">
        <h1 className="text-2xl font-semibold text-neutral-900">Confirm Receipt</h1>
        <p className="mt-1 text-sm text-neutral-500">
          {po.poNumber} — {po.title}
        </p>
      </div>
      <ReceiptForm poId={po.id} />
    </div>
  );
}
