import "server-only";

import { Query } from "node-appwrite";

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

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

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