import "server-only";

import { Query } from "node-appwrite";

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

export async function listCustomers(tenantId: string): Promise<Customer[]> {
  try {
    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 result.rows as unknown as Customer[];
  } catch {
    return [];
  }
}

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