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

type OrderByField = "createdAt";

export interface ListItemValuationsInput extends PaginationInput<OrderByField> {
  itemIds?: string[];
  valuationPolicyId?: string;
}

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

  let query = db.selectFrom("ItemValuation").selectAll();

  if (input.itemIds && input.itemIds.length > 0) {
    query = query.where("itemId", "in", input.itemIds);
  }
  if (input.valuationPolicyId) {
    query = query.where("valuationPolicyId", "=", input.valuationPolicyId);
  }

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

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