import { NextResponse } from "next/server"
import { and, desc, eq, sql } from "drizzle-orm"
import { db } from "@/lib/db"
import { tenants, units } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { tenantSchema } from "@/lib/validations"
import { ownsProperty, ownsUnit } from "@/lib/db/ownership"
import { getUserPlan } from "@/lib/plan-limits"
import { checkLimit } from "@/lib/stripe/plans"
import { logActivity } from "@/lib/activity"
import { getEffectiveOwnerId, getAccountContext } from "@/lib/account"
import { emitWebhookEvent } from "@/lib/webhooks/emit"

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

  const ownerId = await getEffectiveOwnerId(user.id)

  const { searchParams } = new URL(request.url)
  const propertyId = searchParams.get("property_id")
  const status = searchParams.get("status") ?? "active"
  const page = Math.max(1, parseInt(searchParams.get("page") ?? "1", 10))
  const limit = Math.min(100, Math.max(1, parseInt(searchParams.get("limit") ?? "50", 10)))
  const offset = (page - 1) * limit

  const validStatuses = ["active", "inactive", "archived"]
  if (!validStatuses.includes(status)) {
    return NextResponse.json({ error: "Invalid status" }, { status: 400 })
  }

  const where = and(
    eq(tenants.user_id, ownerId),
    eq(tenants.status, status as typeof tenants.$inferSelect.status),
    propertyId ? eq(tenants.property_id, propertyId) : undefined
  )

  const [data, [{ count }]] = await Promise.all([
    db.query.tenants.findMany({
      where,
      with: {
        unit: { columns: { unit_number: true, rent_amount: true } },
        property: { columns: { name: true } },
      },
      orderBy: desc(tenants.created_at),
      limit,
      offset,
    }),
    db.select({ count: sql<number>`count(*)::int` }).from(tenants).where(where),
  ])

  return NextResponse.json({ data, total: count ?? 0, page, limit })
}

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 = tenantSchema.safeParse(body)
  if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 })

  // Enforce per-plan tenant limit (Starter = 3).
  const plan = await getUserPlan(ownerId)
  const [{ count }] = await db
    .select({ count: sql<number>`count(*)::int` })
    .from(tenants)
    .where(eq(tenants.user_id, ownerId))
  if (!checkLimit(plan, "maxTenants", count)) {
    return NextResponse.json(
      { error: "Plan limit reached. Upgrade to add more tenants." },
      { status: 403 }
    )
  }

  if (
    !(await ownsProperty(ownerId, parsed.data.property_id)) ||
    !(await ownsUnit(ownerId, parsed.data.unit_id))
  ) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 })
  }

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

  // Mark unit as occupied — verify unit belongs to the submitted property first
  if (parsed.data.unit_id) {
    const unit = await db.query.units.findFirst({
      where: and(
        eq(units.id, parsed.data.unit_id),
        eq(units.property_id, parsed.data.property_id),
        eq(units.user_id, ownerId)
      ),
      columns: { id: true },
    })

    if (unit) {
      await db
        .update(units)
        .set({ status: "occupied", current_tenant_id: tenant.id })
        .where(and(eq(units.id, parsed.data.unit_id), eq(units.user_id, ownerId)))
    }
  }

  await logActivity({
    userId: ownerId,
    type: "tenant_added",
    title: `New tenant added: ${parsed.data.first_name} ${parsed.data.last_name}`,
    description: parsed.data.email ?? undefined,
    entityType: "tenant",
    entityId: tenant.id,
  })

  await emitWebhookEvent({ ownerId, event: "tenant.created", data: { tenant } })

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