import { NextResponse } from "next/server"
import { and, eq, sql } from "drizzle-orm"
import { db } from "@/lib/db"
import { rent_payments, profiles } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { sendEmail, paymentLinkHtml } from "@/lib/email/send"
import { paymentLinkSchema } from "@/lib/validations"
import { getAccountContext } from "@/lib/account"

export async function POST(request: Request) {
  const user = await getSessionUser()
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

  const ctx = await getAccountContext(user.id)
  const ownerId = ctx.ownerId
  if (!ctx.canWrite) return NextResponse.json({ error: "Forbidden" }, { status: 403 })

  const body = await request.json()
  const parsed = paymentLinkSchema.safeParse(body)
  if (!parsed.success) {
    return NextResponse.json({ error: parsed.error.issues[0]?.message ?? "Invalid payment ID" }, { status: 400 })
  }

  const { payment_id } = parsed.data

  // Fetch payment with tenant details
  const payment = await db.query.rent_payments.findFirst({
    where: and(eq(rent_payments.id, payment_id), eq(rent_payments.user_id, ownerId)),
    with: {
      tenant: { columns: { first_name: true, last_name: true, email: true } },
      property: { columns: { name: true } },
      unit: { columns: { unit_number: true } },
    },
  })

  if (!payment) return NextResponse.json({ error: "Payment not found" }, { status: 404 })
  if (!payment.tenant?.email) return NextResponse.json({ error: "Tenant has no email address" }, { status: 400 })

  // Fetch landlord (portfolio owner) profile for payment instructions
  const profile = await db.query.profiles.findFirst({
    where: eq(profiles.id, ownerId),
    columns: { full_name: true },
  })

  const tenantName = `${payment.tenant.first_name} ${payment.tenant.last_name}`
  const amount = Number(payment.amount).toLocaleString("en-US", { style: "currency", currency: "USD" })
  const dueDate = new Date(payment.due_date).toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" })

  const propertyLabel = `${payment.property?.name ?? "your property"}${
    payment.unit ? ` — Unit ${payment.unit.unit_number}` : ""
  }`

  const html = paymentLinkHtml({
    tenantName,
    amount,
    dueDate,
    propertyLabel,
    senderName: profile?.full_name ?? "Your Landlord",
  })

  try {
    await sendEmail({
      to: payment.tenant.email,
      subject: `Rent Payment Due — ${amount} on ${dueDate}`,
      html,
    })
  } catch {
    return NextResponse.json({ error: "Failed to send email" }, { status: 500 })
  }

  // Update rent_payment to mark reminder sent
  try {
    await db.execute(
      sql`update rent_payments set reminder_sent_at = now() where id = ${payment_id} and user_id = ${ownerId}`
    )
  } catch {
    // Email sent successfully, but tracking update failed — still return ok
    return NextResponse.json({ ok: true, message: `Payment reminder sent to ${payment.tenant.email} (tracking update failed)` })
  }

  return NextResponse.json({ ok: true, message: `Payment reminder sent to ${payment.tenant.email}` })
}
