import "server-only";

import { Query } from "node-appwrite";

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

export async function listPatients(
  clinicTenantId: string,
  options: { includeArchived?: boolean } = {},
): Promise<Patient[]> {
  const { tablesDB } = createAdminClient();
  const queries = [
    Query.equal("clinicTenantId", clinicTenantId),
    Query.orderDesc("$createdAt"),
    Query.limit(500),
  ];
  if (!options.includeArchived) {
    queries.push(Query.notEqual("archived", true));
  }
  const result = await tablesDB.listRows({
    databaseId: DATABASE_ID,
    tableId: TABLES.patients,
    queries,
  });
  return toPlain(result.rows as unknown as Patient[]);
}

export async function getPatient(
  patientId: string,
  clinicTenantId: string,
): Promise<Patient | null> {
  try {
    const { tablesDB } = createAdminClient();
    const row = (await tablesDB.getRow(
      DATABASE_ID,
      TABLES.patients,
      patientId,
    )) as unknown as Patient;
    if (row.clinicTenantId !== clinicTenantId) return null;
    return toPlain(row);
  } catch {
    return null;
  }
}
