import { NextResponse } from "next/server"
import { and, eq } from "drizzle-orm"
import { db } from "@/lib/db"
import { rent_payments } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { createRentPaymentLink } from "@/lib/stripe/payment-links"
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 { payment_id } = await request.json() as { payment_id: string }

  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 } },
      property: { columns: { name: true } },
      unit: { columns: { unit_number: true } },
    },
  })

  if (!payment) return NextResponse.json({ error: "Payment not found" }, { status: 404 })

  const link = await createRentPaymentLink({
    tenantName: `${payment.tenant.first_name} ${payment.tenant.last_name}`,
    propertyName: payment.property.name,
    unitNumber: payment.unit?.unit_number ?? "—",
    amount: payment.amount,
    tenantId: payment.tenant_id,
    paymentId: payment.id,
  })

  // Save link ID to payment record
  await db
    .update(rent_payments)
    .set({ stripe_payment_link_id: link.id })
    .where(and(eq(rent_payments.id, payment_id), eq(rent_payments.user_id, ownerId)))

  return NextResponse.json({ url: link.url })
}
