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

export interface GetWorkOrderInput {
  id: string;
}

export async function run(db: ReadonlyDB<DB>, input: GetWorkOrderInput) {
  const workOrder = await db
    .selectFrom("WorkOrder")
    .selectAll()
    .where("id", "=", input.id)
    .executeTakeFirst();

  if (!workOrder) {
    return err(new WorkOrderNotFoundError(input.id));
  }

  const executionEvents = await db
    .selectFrom("WorkOrderExecutionEvent")
    .selectAll()
    .where("workOrderId", "=", workOrder.id)
    .orderBy("timestamp", "asc")
    .execute();

  return ok({ workOrder, executionEvents });
}
