import { redirect } from "next/navigation"
import { and, eq } from "drizzle-orm"
import { db } from "@/lib/db"
import { leases as leasesTable } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { BulkGenerateForm } from "./bulk-generate-form"

export const metadata = { title: "Generate Rent" }

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

  const leases = await db.query.leases.findMany({
    where: and(eq(leasesTable.user_id, user.id), eq(leasesTable.status, "active")),
    columns: { id: true, rent_amount: true },
    with: {
      tenant: { columns: { first_name: true, last_name: true } },
      property: { columns: { name: true } },
      unit: { columns: { unit_number: true } },
    },
  })

  return (
    <div className="max-w-2xl mx-auto space-y-6">
      <div>
        <h2 className="text-lg font-bold text-white">Generate Monthly Rent</h2>
        <p className="text-sm text-white/40 mt-0.5">
          Create pending rent payments for all active tenants in one click
        </p>
      </div>
      <BulkGenerateForm leases={leases ?? []} />
    </div>
  )
}
