import { ok, err, type ReadonlyDB, type PaginationInput, buildPaginatedResult, DEFAULT_PAGE_SIZE, } from "@tailor-platform/erp-kit/core"; import type { DB } from "../generated/kysely-tailordb"; import { LeaveGrantNotFoundError } from "../lib/errors.generated"; export interface ListLeaveConsumptionByGrantInput extends PaginationInput { leaveGrantId: string; } export async function run(db: ReadonlyDB, input: ListLeaveConsumptionByGrantInput) { const leaveGrant = await db .selectFrom("LeaveGrant") .select("id") .where("id", "=", input.leaveGrantId) .executeTakeFirst(); if (!leaveGrant) { return err(new LeaveGrantNotFoundError(input.leaveGrantId)); } const limit = input.limit ?? DEFAULT_PAGE_SIZE; const offset = input.offset ?? 0; const orderBy = input.orderBy ?? "id"; const orderDirection = input.orderDirection ?? "asc"; const consumptions = await db .selectFrom("LeaveConsumption") .selectAll() .where("leaveGrantId", "=", input.leaveGrantId) .orderBy(orderBy, orderDirection) .limit(limit + 1) .offset(offset) .execute(); return ok(buildPaginatedResult(consumptions, limit)); }