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 { getEffectiveOwnerId } from "@/lib/account"
import { ExpenseForm } from "@/components/forms/expense-form"
import { BackButton } from "@/components/ui/back-button"

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

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

  const ownerId = await getEffectiveOwnerId(user.id)

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

  return (
    <div className="mx-auto max-w-2xl space-y-6">
      <BackButton href="/expenses" />
      <div>
        <h2 className="text-lg font-semibold text-white">Add Expense</h2>
        <p className="text-sm text-white/40">Log a property expense</p>
      </div>
      <ExpenseForm properties={propertyList ?? []} />
    </div>
  )
}
