import type { Transaction } from "../generated/kysely-tailordb";
import { InternalOrderNotFoundError, InvalidStateError } from "../lib/errors.generated";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

export interface DeleteInternalOrderInput {
  internalOrderId: string;
}

export async function run(db: Transaction, input: DeleteInternalOrderInput, ctx: CommandContext) {
  void ctx;

  const order = await db
    .selectFrom("InternalOrder")
    .selectAll()
    .where("id", "=", input.internalOrderId)
    .forUpdate()
    .executeTakeFirst();

  if (!order) {
    return err(new InternalOrderNotFoundError(input.internalOrderId));
  }

  if (order.status !== "CREATED") {
    return err(new InvalidStateError(input.internalOrderId));
  }

  // Remove associated budget assignments
  await db
    .deleteFrom("Budget")
    .where("costObjectId", "=", input.internalOrderId)
    .where("costObjectType", "=", "InternalOrder")
    .execute();

  await db.deleteFrom("InternalOrder").where("id", "=", input.internalOrderId).executeTakeFirst();

  return ok({ internalOrder: order });
}
