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

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

export interface ListSalesPriceListsInput extends PaginationInput<OrderByField> {
  companyId: string;
  status?: string;
}

export async function run(db: ReadonlyDB<DB>, input: ListSalesPriceListsInput) {
  if (!input.companyId) {
    return err(new CompanyScopeRequiredError("sales-price-lists"));
  }
  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("SalesPriceList").selectAll().where("companyId", "=", input.companyId);
  if (input.status) {
    query = query.where("status", "=", input.status as never);
  }

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