import type { AuditLogPage, AuditLogQuery } from '@admin/actions/audit/types' import { buildAuditLogWhere } from '@admin/actions/audit/build-audit-log-where' import { clampPage } from '@admin/actions/audit/clamp-page' import { getAuditLogOrderBy } from '@admin/actions/audit/get-audit-log-order-by' import { normalizePageSize } from '@admin/actions/audit/normalize-page-size' import db from '@admin/db' import { auditLog } from '@admin/db/schema' import { sql } from 'drizzle-orm' export async function queryAuditLogs(query: AuditLogQuery = {}): Promise { const page = clampPage(query.page) const pageSize = normalizePageSize(query.pageSize) const offset = pageSize ? page * pageSize : 0 const where = buildAuditLogWhere(query) const orderBy = getAuditLogOrderBy(query) const orderedQuery = db .select() .from(auditLog) .where(where) .orderBy(...orderBy) const [rows, countResult] = await Promise.all([ pageSize ? orderedQuery.limit(pageSize).offset(offset) : orderedQuery, db .select({ count: sql`count(*)` }) .from(auditLog) .where(where) ]) const total = Number(countResult[0]?.count ?? 0) const resolvedPageSize = pageSize ?? total return { auditLogs: rows, total, page, pageSize: resolvedPageSize, totalPages: pageSize ? Math.max(1, Math.ceil(total / pageSize)) : 1 } }