import type { DB } from "../generated/kysely-tailordb";
import { WorkCenterReferenceRequiredError, WorkCenterNotFoundError } 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 ListWorkOrdersByWorkCenterInput extends PaginationInput<OrderByField> {
  workCenterId: string;
  status?: string;
}

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

  const workCenter = await db
    .selectFrom("WorkCenter")
    .selectAll()
    .where("id", "=", input.workCenterId)
    .executeTakeFirst();

  if (!workCenter) {
    return err(new WorkCenterNotFoundError(input.workCenterId));
  }

  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("workCenterId", "=", input.workCenterId);

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

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

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