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

type OrderByField = "revisionNumber";

export interface ListRoutingsByItemInput extends PaginationInput<OrderByField> {
  companyId: string;
  parentItemId: string;
  siteId?: string;
  status?: RoutingStatus;
}

export async function run(db: ReadonlyDB<DB>, input: ListRoutingsByItemInput) {
  if (!input.companyId) {
    return err(new CompanyScopeRequiredError("missing"));
  }
  if (!input.parentItemId) {
    return err(new ParentItemRequiredError("missing"));
  }

  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "revisionNumber";
  const orderDirection = input.orderDirection ?? "asc";

  let query = db
    .selectFrom("Routing")
    .selectAll()
    .where("companyId", "=", input.companyId)
    .where("parentItemId", "=", input.parentItemId);

  if (input.siteId) {
    query = query.where("siteId", "=", input.siteId);
  }
  if (input.status) {
    query = query.where("status", "=", input.status);
  }

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

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