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 { LeaveRequestNotFoundError } from "../lib/errors.generated"; export interface ListLeaveConsumptionByRequestInput extends PaginationInput { leaveRequestId: string; } export async function run(db: ReadonlyDB, input: ListLeaveConsumptionByRequestInput) { const leaveRequest = await db .selectFrom("LeaveRequest") .select("id") .where("id", "=", input.leaveRequestId) .executeTakeFirst(); if (!leaveRequest) { return err(new LeaveRequestNotFoundError(input.leaveRequestId)); } 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("leaveRequestId", "=", input.leaveRequestId) .orderBy(orderBy, orderDirection) .limit(limit + 1) .offset(offset) .execute(); return ok(buildPaginatedResult(consumptions, limit)); }