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

type SPT = Selectable<"SalesPaymentTerm">;
type OrderByField = "createdAt" | "name" | "status";

export type ListSalesPaymentTermsInput = Pick<SPT, "companyId"> &
  Partial<Pick<SPT, "status">> &
  PaginationInput<OrderByField>;

export async function run(db: ReadonlyDB<DB>, input: ListSalesPaymentTermsInput) {
  if (!input.companyId) {
    return err(new CompanyScopeRequiredError("sales-payment-terms"));
  }
  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("SalesPaymentTerm")
    .selectAll()
    .where("companyId", "=", input.companyId);
  if (input.status) {
    query = query.where("status", "=", input.status);
  }

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