import "server-only";

import { Query } from "node-appwrite";

import { canAccessRow } from "./scope-permissions";
import { createAdminClient } from "./server";
import {
  DATABASE_ID,
  TABLES,
  type CreditCard,
  type CreditCardStatement,
} from "./schema";

export async function listCreditCards(
  tenantId: string,
  currentUserId?: string,
): Promise<CreditCard[]> {
  try {
    const { tablesDB } = createAdminClient();
    const result = await tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.creditCards,
      queries: [
        Query.equal("tenantId", tenantId),
        Query.orderAsc("bankName"),
        Query.limit(200),
      ],
    });
    const rows = result.rows as unknown as CreditCard[];
    if (!currentUserId) return rows;
    return rows.filter((r) => canAccessRow(r, currentUserId));
  } catch {
    return [];
  }
}

/**
 * Lists statements whose parent card is visible to the user.
 */
export async function listStatements(
  tenantId: string,
  currentUserId?: string,
): Promise<CreditCardStatement[]> {
  try {
    const { tablesDB } = createAdminClient();
    const [allStmt, allCards] = await Promise.all([
      tablesDB.listRows({
        databaseId: DATABASE_ID,
        tableId: TABLES.creditCardStatements,
        queries: [
          Query.equal("tenantId", tenantId),
          Query.orderDesc("statementDate"),
          Query.limit(500),
        ],
      }),
      tablesDB.listRows({
        databaseId: DATABASE_ID,
        tableId: TABLES.creditCards,
        queries: [Query.equal("tenantId", tenantId), Query.limit(200)],
      }),
    ]);
    if (!currentUserId) return allStmt.rows as unknown as CreditCardStatement[];
    const visibleCardIds = new Set(
      (allCards.rows as unknown as CreditCard[])
        .filter((c) => canAccessRow(c, currentUserId))
        .map((c) => c.$id),
    );
    return (allStmt.rows as unknown as CreditCardStatement[]).filter((s) =>
      visibleCardIds.has(s.cardId),
    );
  } catch {
    return [];
  }
}
