import { NextResponse } from "next/server" import { and, desc, eq, sql } from "drizzle-orm" import { db } from "@/lib/db" import { properties, profiles } from "@/lib/db/schema" import { getSessionUser } from "@/lib/session" import { propertySchema } from "@/lib/validations" export async function GET() { const user = await getSessionUser() if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }) const data = await db.query.properties.findMany({ where: eq(properties.user_id, user.id), with: { units: { columns: { id: true, status: true } } }, orderBy: desc(properties.created_at), }) return NextResponse.json(data) } export async function POST(request: Request) { const user = await getSessionUser() if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }) const body = await request.json() const parsed = propertySchema.safeParse(body) if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 }) // Check plan limit const [{ count }] = await db .select({ count: sql`count(*)::int` }) .from(properties) .where(eq(properties.user_id, user.id)) const profile = await db.query.profiles.findFirst({ where: eq(profiles.id, user.id), columns: { plan: true }, }) const limits: Record = { starter: 1, pro: 10, landlord: Infinity, lifetime: Infinity } const limit = limits[profile?.plan ?? "starter"] ?? 1 if (count >= limit) { return NextResponse.json({ error: "Plan limit reached. Upgrade to add more properties." }, { status: 403 }) } const [data] = await db .insert(properties) .values({ ...parsed.data, user_id: user.id }) .returning() return NextResponse.json(data, { status: 201 }) }