import "server-only";

import { Query } from "node-appwrite";

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

export async function listClinicPricing(
  labTenantId: string,
  clinicTenantId: string,
): Promise<ClinicPricing[]> {
  const { tablesDB } = createAdminClient();
  const result = await tablesDB.listRows({
    databaseId: DATABASE_ID,
    tableId: TABLES.clinicPricing,
    queries: [
      Query.equal("labTenantId", labTenantId),
      Query.equal("clinicTenantId", clinicTenantId),
      Query.limit(50),
    ],
  });
  return toPlain(result.rows as unknown as ClinicPricing[]);
}

export async function listClinicPricingForClinic(
  clinicTenantId: string,
  labTenantId: string,
): Promise<ClinicPricing[]> {
  return listClinicPricing(labTenantId, clinicTenantId);
}

/** Single bulk query so /connections doesn't N+1 across approved counterparts. */
export async function listAllPricingForLab(
  labTenantId: string,
): Promise<ClinicPricing[]> {
  const { tablesDB } = createAdminClient();
  const result = await tablesDB.listRows({
    databaseId: DATABASE_ID,
    tableId: TABLES.clinicPricing,
    queries: [Query.equal("labTenantId", labTenantId), Query.limit(500)],
  });
  return toPlain(result.rows as unknown as ClinicPricing[]);
}

export async function listAllPricingForClinic(
  clinicTenantId: string,
): Promise<ClinicPricing[]> {
  const { tablesDB } = createAdminClient();
  const result = await tablesDB.listRows({
    databaseId: DATABASE_ID,
    tableId: TABLES.clinicPricing,
    queries: [Query.equal("clinicTenantId", clinicTenantId), Query.limit(500)],
  });
  return toPlain(result.rows as unknown as ClinicPricing[]);
}
