import { ok, type ReadonlyDB, type PaginationInput, buildPaginatedResult, DEFAULT_PAGE_SIZE, } from "@tailor-platform/erp-kit/core"; import type { DepartmentStatus } from "../db/department.lifecycle.generated"; import type { DB } from "../generated/kysely-tailordb"; type DepartmentOrderByField = "name" | "code" | "createdAt"; export interface ListDepartmentsByCompanyInput extends PaginationInput { companyId: string; status?: DepartmentStatus; parentDepartmentId?: string | null; } export async function run(db: ReadonlyDB, input: ListDepartmentsByCompanyInput) { const limit = input.limit ?? DEFAULT_PAGE_SIZE; const offset = input.offset ?? 0; const orderBy = input.orderBy ?? "name"; const orderDirection = input.orderDirection ?? "asc"; let query = db.selectFrom("Department").selectAll().where("companyId", "=", input.companyId); if (input.status !== undefined) { query = query.where("status", "=", input.status); } if (input.parentDepartmentId === null) { query = query.where("parentDepartmentId", "is", null); } else if (input.parentDepartmentId !== undefined) { query = query.where("parentDepartmentId", "=", input.parentDepartmentId); } const departments = await query .orderBy(orderBy, orderDirection) .limit(limit + 1) .offset(offset) .execute(); return ok(buildPaginatedResult(departments, limit)); }