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 { NoFilterProvidedError } from "../lib/errors.generated";

type OrderByField = "createdAt";

export interface ListCostLayersInput extends PaginationInput<OrderByField> {
  itemId?: string;
  valuationPolicyId?: string;
}

export async function run(db: ReadonlyDB<DB>, input: ListCostLayersInput) {
  if (!input.itemId && !input.valuationPolicyId) {
    return err(new NoFilterProvidedError("listCostLayers"));
  }

  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("CostLayer").selectAll();

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

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

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