import { NextResponse } from "next/server"
import { and, desc, eq, gte, lte } from "drizzle-orm"
import { db } from "@/lib/db"
import { rent_payments } from "@/lib/db/schema"
import { rentPaymentSchema } from "@/lib/validations"
import { ownsProperty, ownsUnit, ownsTenant } from "@/lib/db/ownership"
import { resolveApiRequest } from "@/lib/api-auth"
import { emitWebhookEvent } from "@/lib/webhooks/emit"

// Public REST API (v1) — rent payments. Bearer API-key auth. Maps to the
// rent_payments table / internal /api/rent logic. Scoped by resolved owner id.

const unauthorized = () =>
  NextResponse.json({ error: { code: 401, message: "Unauthorized" } }, { status: 401 })
const forbidden = () =>
  NextResponse.json({ error: { code: 403, message: "Forbidden" } }, { status: 403 })

const VALID_STATUSES = ["pending", "paid", "overdue", "partial", "waived"]

export async function GET(request: Request) {
  const ctx = await resolveApiRequest(request)
  if (!ctx) return unauthorized()

  const { searchParams } = new URL(request.url)
  const status = searchParams.get("status")
  const tenantId = searchParams.get("tenant_id")
  // Date-range filter on the payment's due_date ("YYYY-MM-DD").
  const from = searchParams.get("from")
  const to = searchParams.get("to")

  if (status && !VALID_STATUSES.includes(status)) {
    return NextResponse.json(
      { error: { code: 400, message: "Invalid status" } },
      { status: 400 }
    )
  }

  const data = await db.query.rent_payments.findMany({
    where: and(
      eq(rent_payments.user_id, ctx.ownerId),
      status ? eq(rent_payments.status, status as typeof rent_payments.$inferSelect.status) : undefined,
      tenantId ? eq(rent_payments.tenant_id, tenantId) : undefined,
      from ? gte(rent_payments.due_date, from) : undefined,
      to ? lte(rent_payments.due_date, to) : undefined
    ),
    with: {
      tenant: { columns: { first_name: true, last_name: true, email: true } },
      property: { columns: { name: true } },
      unit: { columns: { unit_number: true } },
    },
    orderBy: desc(rent_payments.due_date),
  })

  return NextResponse.json({ data, count: data.length })
}

export async function POST(request: Request) {
  const ctx = await resolveApiRequest(request)
  if (!ctx) return unauthorized()
  if (!ctx.canWrite) return forbidden()

  const body = await request.json().catch(() => null)
  const parsed = rentPaymentSchema.safeParse(body)
  if (!parsed.success) {
    return NextResponse.json(
      { error: { code: 400, message: parsed.error.flatten() } },
      { status: 400 }
    )
  }

  if (
    !(await ownsProperty(ctx.ownerId, parsed.data.property_id)) ||
    !(await ownsUnit(ctx.ownerId, parsed.data.unit_id)) ||
    !(await ownsTenant(ctx.ownerId, parsed.data.tenant_id))
  ) {
    return forbidden()
  }

  const [data] = await db
    .insert(rent_payments)
    .values({ ...parsed.data, user_id: ctx.ownerId })
    .returning()

  await emitWebhookEvent({ ownerId: ctx.ownerId, event: "payment.recorded", data: { payment: data } })
  if (data.status === "paid") {
    await emitWebhookEvent({ ownerId: ctx.ownerId, event: "payment.paid", data: { payment: data } })
  }

  return NextResponse.json({ data }, { status: 201 })
}
