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 CloseInternalOrderInput {
  internalOrderId: string;
  from?: string[];
}

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

  const validFromStatuses = input.from ?? ["TECHNICALLY_COMPLETED"];

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

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

  if (!validFromStatuses.includes(order.status)) {
    return err(new InvalidStateError(input.internalOrderId));
  }

  const updated = await db
    .updateTable("InternalOrder")
    .set({ status: "CLOSED", updatedAt: new Date() })
    .where("id", "=", input.internalOrderId)
    .returningAll()
    .executeTakeFirst();

  return ok({ internalOrder: updated! });
}
