import { redirect } from "next/navigation"
import { asc, eq } from "drizzle-orm"
import { db } from "@/lib/db"
import { properties } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { TenantForm } from "@/components/forms/tenant-form"
import { BackButton } from "@/components/ui/back-button"

export const metadata = { title: "Add Tenant" }

export default async function NewTenantPage() {
  const user = await getSessionUser()
  if (!user) redirect("/login")

  const properties_ = await db.query.properties.findMany({
    where: eq(properties.user_id, user.id),
    columns: { id: true, name: true },
    with: {
      units: { columns: { id: true, unit_number: true, status: true } },
    },
    orderBy: asc(properties.name),
  })

  return (
    <div className="mx-auto max-w-2xl space-y-6">
      <BackButton href="/tenants" />
      <div>
        <h2 className="text-lg font-semibold text-white">Add Tenant</h2>
        <p className="text-sm text-white/40">Add a tenant and assign them to a unit</p>
      </div>
      <TenantForm properties={properties_ ?? []} />
    </div>
  )
}
