import { NextResponse } from "next/server"
import { and, eq, lt, lte } from "drizzle-orm"
import { db } from "@/lib/db"
import { rent_payments, leases } from "@/lib/db/schema"
import { sendEmail, rentDueReminderHtml, rentOverdueHtml, leaseExpiryHtml } from "@/lib/email/send"
import { formatCurrency, formatDate, daysUntil } from "@/lib/utils"
import { isAuthorizedCron } from "@/lib/cron-auth"

// Combined daily cron: rent reminders + overdue marking + lease expiry emails
// Runs daily at 9am UTC (scheduled via DigitalOcean Functions — see DIGITALOCEAN.md)
export async function GET(request: Request) {
  if (!isAuthorizedCron(request)) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
  }

  const today = new Date().toISOString().slice(0, 10)

  // ──────────────────────────────────────
  // 1. RENT REMINDERS (due in 3 days)
  // ──────────────────────────────────────
  const in3Days = new Date()
  in3Days.setDate(in3Days.getDate() + 3)
  const in3DaysStr = in3Days.toISOString().slice(0, 10)

  const upcoming = await db.query.rent_payments.findMany({
    where: and(eq(rent_payments.status, "pending"), eq(rent_payments.due_date, in3DaysStr)),
    with: {
      tenant: { columns: { first_name: true, last_name: true, email: true } },
      property: { columns: { name: true } },
      unit: { columns: { unit_number: true } },
    },
  })

  for (const payment of upcoming) {
    if (!payment.tenant?.email) continue
    await sendEmail({
      to: payment.tenant.email,
      subject: `Rent Due in 3 Days — ${payment.property?.name}`,
      html: rentDueReminderHtml({
        tenantName: `${payment.tenant.first_name} ${payment.tenant.last_name}`,
        propertyName: payment.property?.name ?? "",
        unitNumber: payment.unit?.unit_number ?? "—",
        amount: formatCurrency(payment.amount),
        dueDate: formatDate(payment.due_date),
      }),
    })
  }

  // ──────────────────────────────────────
  // 2. MARK OVERDUE + SEND NOTICE
  // ──────────────────────────────────────
  const pastDue = await db.query.rent_payments.findMany({
    where: and(eq(rent_payments.status, "pending"), lt(rent_payments.due_date, today)),
    with: {
      tenant: { columns: { first_name: true, last_name: true, email: true } },
      property: { columns: { name: true } },
      unit: { columns: { unit_number: true } },
    },
  })

  for (const payment of pastDue) {
    await db
      .update(rent_payments)
      .set({ status: "overdue" })
      .where(eq(rent_payments.id, payment.id))

    if (!payment.tenant?.email) continue
    await sendEmail({
      to: payment.tenant.email,
      subject: `Rent Overdue — ${payment.property?.name}`,
      html: rentOverdueHtml({
        tenantName: `${payment.tenant.first_name} ${payment.tenant.last_name}`,
        propertyName: payment.property?.name ?? "",
        unitNumber: payment.unit?.unit_number ?? "—",
        amount: formatCurrency(payment.amount),
        dueDate: formatDate(payment.due_date),
      }),
    })
  }

  // ──────────────────────────────────────
  // 3. LEASE EXPIRY REMINDERS (60/30/7 days)
  // ──────────────────────────────────────
  const checkpoints = [
    { days: 60, field: "reminder_60_sent" as const },
    { days: 30, field: "reminder_30_sent" as const },
    { days: 7,  field: "reminder_7_sent"  as const },
  ]

  let leaseRemindersSent = 0

  for (const { days, field } of checkpoints) {
    const target = new Date()
    target.setDate(target.getDate() + days)
    const targetStr = target.toISOString().slice(0, 10)

    const expiringLeases = await db.query.leases.findMany({
      where: and(
        eq(leases.status, "active"),
        eq(leases[field], false),
        lte(leases.lease_end, targetStr)
      ),
      with: {
        tenant: { columns: { first_name: true, last_name: true, email: true } },
        property: { columns: { name: true } },
        unit: { columns: { unit_number: true } },
      },
    })

    for (const lease of expiringLeases) {
      if (!lease.tenant?.email) continue

      const daysLeft = daysUntil(lease.lease_end)

      await sendEmail({
        to: lease.tenant.email,
        subject: `Your lease expires in ${daysLeft} days — ${lease.property?.name}`,
        html: leaseExpiryHtml({
          tenantName: `${lease.tenant.first_name} ${lease.tenant.last_name}`,
          propertyName: lease.property?.name ?? "",
          unitNumber: lease.unit?.unit_number ?? "—",
          leaseEnd: formatDate(lease.lease_end),
          daysLeft,
        }),
      })

      await db
        .update(leases)
        .set({ [field]: true })
        .where(eq(leases.id, lease.id))

      leaseRemindersSent++
    }
  }

  return NextResponse.json({
    rent_reminders_sent: upcoming.length,
    marked_overdue: pastDue.length,
    lease_reminders_sent: leaseRemindersSent,
  })
}
