import "server-only";

import { Query } from "node-appwrite";

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

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