import { and, eq } from "drizzle-orm"
import { db } from "@/lib/db"
import { properties, units, tenants } from "@/lib/db/schema"

/** True if the property belongs to the user. Null/undefined/empty id returns true (FK optional). */
export async function ownsProperty(userId: string, id?: string | null): Promise<boolean> {
  if (!id) return true
  const row = await db.query.properties.findFirst({
    where: and(eq(properties.id, id), eq(properties.user_id, userId)),
    columns: { id: true },
  })
  return !!row
}

export async function ownsUnit(userId: string, id?: string | null): Promise<boolean> {
  if (!id) return true
  const row = await db.query.units.findFirst({
    where: and(eq(units.id, id), eq(units.user_id, userId)),
    columns: { id: true },
  })
  return !!row
}

export async function ownsTenant(userId: string, id?: string | null): Promise<boolean> {
  if (!id) return true
  const row = await db.query.tenants.findFirst({
    where: and(eq(tenants.id, id), eq(tenants.user_id, userId)),
    columns: { id: true },
  })
  return !!row
}
