import "server-only";

import { Query } from "node-appwrite";

import { DATABASE_ID, TABLES, type Property } from "./schema";
import { createAdminClient } from "./server";

export async function listProperties(tenantId: string): Promise<Property[]> {
  const { tablesDB } = createAdminClient();
  const result = await tablesDB.listRows({
    databaseId: DATABASE_ID,
    tableId: TABLES.properties,
    queries: [Query.equal("tenantId", tenantId), Query.orderDesc("$createdAt"), Query.limit(200)],
  });
  return JSON.parse(JSON.stringify(result.rows)) as Property[];
}

export async function getProperty(id: string, tenantId: string): Promise<Property | null> {
  const { tablesDB } = createAdminClient();
  const row = (await tablesDB.getRow(DATABASE_ID, TABLES.properties, id)) as unknown as Property;
  if (row.tenantId !== tenantId) return null;
  return JSON.parse(JSON.stringify(row)) as Property;
}
