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

type OrderByField = "name" | "createdAt";

export interface ListValuationPoliciesInput extends PaginationInput<OrderByField> {
  costingMethod?: ValuationPolicyCostingMethod;
}

export async function run(db: ReadonlyDB<DB>, input: ListValuationPoliciesInput) {
  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("ValuationPolicy").selectAll();

  if (input.costingMethod) {
    query = query.where("costingMethod", "=", input.costingMethod);
  }

  const valuationPolicies = await query
    .orderBy(orderBy, orderDirection)
    .limit(limit + 1)
    .offset(offset)
    .execute();

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