import "server-only";

import { Query } from "node-appwrite";

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

export async function listServices(tenantId: string): Promise<Service[]> {
  try {
    const { tablesDB } = createAdminClient();
    const result = await tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.services,
      queries: [
        Query.equal("tenantId", tenantId),
        Query.orderDesc("$createdAt"),
        Query.limit(500),
      ],
    });
    return result.rows as unknown as Service[];
  } catch {
    return [];
  }
}

export async function listServicesByCustomer(
  tenantId: string,
  customerId: string,
): Promise<Service[]> {
  try {
    const { tablesDB } = createAdminClient();
    const result = await tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.services,
      queries: [
        Query.equal("tenantId", tenantId),
        Query.equal("customerId", customerId),
        Query.orderDesc("$createdAt"),
        Query.limit(500),
      ],
    });
    return result.rows as unknown as Service[];
  } catch {
    return [];
  }
}
