import { redirect } from "next/navigation"
import { asc, desc, eq } from "drizzle-orm"
import { db } from "@/lib/db"
import { expenses, properties } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { getEffectiveOwnerId } from "@/lib/account"
import { ExpensesClient } from "./expenses-client"

export const metadata = { title: "Expenses" }

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

  const ownerId = await getEffectiveOwnerId(user.id)

  const [expenseList, propertyList] = await Promise.all([
    db.query.expenses.findMany({
      where: eq(expenses.user_id, ownerId),
      with: {
        property: { columns: { name: true } },
        unit: { columns: { unit_number: true } },
      },
      orderBy: desc(expenses.expense_date),
    }),
    db
      .select({ id: properties.id, name: properties.name })
      .from(properties)
      .where(eq(properties.user_id, ownerId))
      .orderBy(asc(properties.name)),
  ])

  return (
    <ExpensesClient
      expenses={expenseList ?? []}
      properties={propertyList ?? []}
    />
  )
}
