import {
  ok,
  type ReadonlyDB,
  type PaginationInput,
  buildPaginatedResult,
  DEFAULT_PAGE_SIZE,
} from "@tailor-platform/erp-kit/core";
import type { DB } from "../generated/kysely-tailordb";

type UnitOrderByField = "name" | "symbol" | "createdAt";

export interface ListUnitsByCategoryInput extends PaginationInput<UnitOrderByField> {
  categoryId: string;
}

export async function run(db: ReadonlyDB<DB>, input: ListUnitsByCategoryInput) {
  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "id";
  const orderDirection = input.orderDirection ?? "asc";

  const units = await db
    .selectFrom("Unit")
    .selectAll()
    .where("categoryId", "=", input.categoryId)
    .orderBy(orderBy, orderDirection)
    .limit(limit + 1)
    .offset(offset)
    .execute();

  return ok(buildPaginatedResult(units, limit));
}
