import { redirect } from "next/navigation"
import { and, eq, gte, lte } from "drizzle-orm"
import { db } from "@/lib/db"
import { rent_payments, leases } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { CalendarClient } from "./calendar-client"

export const metadata = { title: "Calendar" }

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

  const now = new Date()
  const rangeStart = new Date(now.getFullYear(), now.getMonth() - 1, 1)
  const rangeEnd = new Date(now.getFullYear(), now.getMonth() + 3, 0)

  const [payments, leaseList] = await Promise.all([
    db.query.rent_payments.findMany({
      where: and(
        eq(rent_payments.user_id, user.id),
        gte(rent_payments.due_date, rangeStart.toISOString().slice(0, 10)),
        lte(rent_payments.due_date, rangeEnd.toISOString().slice(0, 10))
      ),
      columns: { id: true, due_date: true, amount: true, status: true },
      with: {
        tenant: { columns: { first_name: true, last_name: true } },
      },
    }),
    db.query.leases.findMany({
      where: and(
        eq(leases.user_id, user.id),
        gte(leases.lease_end, new Date().toISOString().slice(0, 10))
      ),
      columns: { id: true, lease_end: true },
      with: {
        tenant: { columns: { first_name: true, last_name: true } },
        property: { columns: { name: true } },
      },
    }),
  ])

  return (
    <div className="max-w-5xl mx-auto">
      <div className="mb-6">
        <h2 className="text-lg font-bold text-white">Calendar</h2>
        <p className="text-sm text-white/40 mt-0.5">Rent due dates and lease expirations at a glance</p>
      </div>
      <CalendarClient payments={payments ?? []} leases={leaseList ?? []} />
    </div>
  )
}
