import "server-only";

import { Query } from "node-appwrite";

import { DATABASE_ID, TABLES, type Prosthetic } from "./schema";
import { createAdminClient } from "./server";
import { toPlain } from "./serialize";

export async function listProsthetics(tenantId: string): Promise<Prosthetic[]> {
  const { tablesDB } = createAdminClient();
  const result = await tablesDB.listRows({
    databaseId: DATABASE_ID,
    tableId: TABLES.prosthetics,
    queries: [
      Query.equal("tenantId", tenantId),
      Query.orderAsc("name"),
      Query.limit(200),
    ],
  });
  return toPlain(result.rows as unknown as Prosthetic[]);
}

export async function listActiveProsthetics(tenantId: string): Promise<Prosthetic[]> {
  const { tablesDB } = createAdminClient();
  const result = await tablesDB.listRows({
    databaseId: DATABASE_ID,
    tableId: TABLES.prosthetics,
    queries: [
      Query.equal("tenantId", tenantId),
      Query.notEqual("archived", true),
      Query.orderAsc("name"),
      Query.limit(200),
    ],
  });
  return toPlain(result.rows as unknown as Prosthetic[]);
}
