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

type OrderByField = "routingOperationSequenceNumber";

export interface ListWorkOrdersByProductionOrderInput extends PaginationInput<OrderByField> {
  productionOrderId: string;
  status?: string;
  workCenterId?: string;
}

export async function run(db: ReadonlyDB<DB>, input: ListWorkOrdersByProductionOrderInput) {
  if (!input.productionOrderId) {
    return err(new ProductionOrderReferenceRequiredError("missing"));
  }

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

  let query = db
    .selectFrom("WorkOrder")
    .selectAll()
    .where("productionOrderId", "=", input.productionOrderId);

  if (input.status) {
    query = query.where(
      "status",
      "=",
      input.status as "PENDING" | "IN_PROGRESS" | "PAUSED" | "COMPLETE" | "CANCELLED",
    );
  }
  if (input.workCenterId) {
    query = query.where("workCenterId", "=", input.workCenterId);
  }

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

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