import "server-only";

import { Query } from "node-appwrite";

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

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

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