import "server-only";

import { Query } from "node-appwrite";

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

export async function listFinanceEntries(
  tenantId: string,
  currentUserId?: string,
): Promise<FinanceEntry[]> {
  try {
    const { tablesDB } = createAdminClient();
    const result = await tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.financeEntries,
      queries: [
        Query.equal("tenantId", tenantId),
        Query.orderDesc("date"),
        Query.limit(1000),
      ],
    });
    const rows = result.rows as unknown as FinanceEntry[];
    if (!currentUserId) return rows;
    return rows.filter((r) => canAccessRow(r, currentUserId));
  } catch {
    return [];
  }
}
