import {redirect} from "next/navigation";
import {auth} from "@/auth";
import {prisma} from "@/lib/db/prisma";
import {getTenantDb} from "@/lib/db/tenant";
import {NewVehicleForm} from "./new-vehicle-form";

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

export default async function NewVehiclePage({params}: NewVehiclePageProps) {
  const {tenantSlug, locale} = await params;
  const session = await auth();
  if (!session?.user?.id) redirect(`/${locale}/auth/sign-in`);

  const tenant = await prisma.tenant.findUnique({where: {slug: tenantSlug}});
  if (!tenant) redirect(`/${locale}/auth/sign-in`);

  const db = getTenantDb(tenant.id);
  const [branches, brands] = await Promise.all([
    db.branch.findMany({where: {isActive: true}, orderBy: {name: "asc"}}),
    prisma.vehicleBrand.findMany({
      where: {isActive: true},
      include: {models: true},
      orderBy: {name: "asc"}
    })
  ]);

  return (
    <NewVehicleForm
      tenantSlug={tenantSlug}
      branches={branches.map((b) => ({id: b.id, name: b.name}))}
      brands={brands.map((b) => ({
        id: b.id,
        name: b.name,
        models: b.models.map((m) => ({id: m.id, name: m.name}))
      }))}
    />
  );
}
