import "server-only";

import { Query } from "node-appwrite";

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

export async function listSavedCards(tenantId: string): Promise<SavedCard[]> {
  const { tablesDB } = createAdminClient();
  const result = await tablesDB.listRows({
    databaseId: DATABASE_ID,
    tableId: TABLES.savedCards,
    queries: [
      Query.equal("tenantId", tenantId),
      Query.orderDesc("isDefault"),
      Query.orderDesc("$createdAt"),
      Query.limit(20),
    ],
  });
  return result.rows as unknown as SavedCard[];
}

export async function getDefaultCard(tenantId: string): Promise<SavedCard | null> {
  const { tablesDB } = createAdminClient();
  const result = await tablesDB.listRows({
    databaseId: DATABASE_ID,
    tableId: TABLES.savedCards,
    queries: [
      Query.equal("tenantId", tenantId),
      Query.equal("isDefault", true),
      Query.limit(1),
    ],
  });
  return (result.rows[0] as unknown as SavedCard) ?? null;
}
