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

export interface GetRoutingInput {
  id: string;
  companyId: string;
}

export async function run(db: ReadonlyDB<DB>, input: GetRoutingInput) {
  if (!input.companyId) {
    return err(new CompanyScopeRequiredError(input.id));
  }

  const routing = await db
    .selectFrom("Routing")
    .selectAll()
    .where("id", "=", input.id)
    .where("companyId", "=", input.companyId)
    .executeTakeFirst();

  if (!routing) {
    return err(new RoutingNotFoundError(input.id));
  }

  const operations = await db
    .selectFrom("RoutingOperation")
    .selectAll()
    .where("routingId", "=", routing.id)
    .orderBy("sequenceNumber", "asc")
    .execute();

  return ok({ routing, operations });
}
