import {notFound} from "next/navigation";
import {prisma} from "@/lib/db/prisma";
import {getTenantDb} from "@/lib/db/tenant";
import {NewContractForm} from "./new-contract-form";

type NewContractPageProps = {
  params: Promise<{tenantSlug: string}>;
};

export default async function NewContractPage({params}: NewContractPageProps) {
  const {tenantSlug} = await params;

  const tenant = await prisma.tenant.findUnique({where: {slug: tenantSlug}});
  if (!tenant) notFound();

  const db = getTenantDb(tenant.id);

  // Get bookings without contracts, that are confirmed or active
  const existingContractBookingIds = await db.rentalContract.findMany({
    select: {bookingId: true}
  });
  const excludedIds = existingContractBookingIds.map((c) => c.bookingId);

  const bookings = await db.booking.findMany({
    where: {
      status: {in: ["CONFIRMED", "ACTIVE"]},
      ...(excludedIds.length > 0 ? {id: {notIn: excludedIds}} : {})
    },
    include: {
      customerProfile: {include: {user: {select: {firstName: true, lastName: true, phone: true}}}},
      vehicle: {select: {name: true, plateNumber: true}},
      pickupBranch: {select: {name: true}},
      dropoffBranch: {select: {name: true}}
    },
    orderBy: {createdAt: "desc"},
    take: 50
  });

  const formBookings = bookings.map((b) => ({
    id: b.id,
    bookingNumber: b.bookingNumber,
    customerName: [b.customerProfile.user.firstName, b.customerProfile.user.lastName].filter(Boolean).join(" ") || b.customerProfile.user.firstName || "Unknown",
    vehicleName: b.vehicle.name,
    vehiclePlate: b.vehicle.plateNumber,
    pickupAt: b.pickupAt,
    dropoffAt: b.dropoffAt,
    dailyRate: Number(b.dailyRate),
    totalAmount: Number(b.totalAmount),
    depositAmount: Number(b.depositAmount),
    pickupLocation: b.pickupBranch.name,
    dropoffLocation: b.dropoffBranch.name
  }));

  return (
    <div className="mx-auto max-w-3xl space-y-6 p-6">
      <div>
        <h1 className="text-2xl font-bold text-slate-900">New Rental Contract</h1>
        <p className="mt-1 text-slate-500">Create a rental contract linked to a booking</p>
      </div>
      <NewContractForm
        tenantId={tenant.id}
        tenantSlug={tenantSlug}
        currency={tenant.currency}
        bookings={formBookings}
      />
    </div>
  );
}
