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

type OrderByField = "createdAt" | "minimumQuantity" | "priority" | "status";

export interface ListSalesPriceRulesByPriceListInput extends PaginationInput<OrderByField> {
  salesPriceListId: string;
  status?: string;
}

export async function run(db: ReadonlyDB<DB>, input: ListSalesPriceRulesByPriceListInput) {
  const priceList = await db
    .selectFrom("SalesPriceList")
    .selectAll()
    .where("id", "=", input.salesPriceListId)
    .executeTakeFirst();
  if (!priceList) {
    return err(new PriceListNotFoundError(input.salesPriceListId));
  }
  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "priority";
  const orderDirection = input.orderDirection ?? "desc";

  let query = db
    .selectFrom("SalesPriceRule")
    .selectAll()
    .where("salesPriceListId", "=", input.salesPriceListId);
  if (input.status) {
    query = query.where("status", "=", input.status as never);
  }

  const rules = await query
    .orderBy(orderBy, orderDirection)
    .limit(limit + 1)
    .offset(offset)
    .execute();
  return ok(buildPaginatedResult(rules, limit));
}
