import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import { inventoryExecutionLifecycle } from "../db/inventoryExecution.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import { InvalidStatusError } from "../lib/errors.generated";

export interface CancelGoodsReceiptInput {
  id: string;
}

export async function run(db: Transaction, input: CancelGoodsReceiptInput, _ctx: CommandContext) {
  const inventoryExecution = await db
    .selectFrom("InventoryExecution")
    .selectAll()
    .where("id", "=", input.id)
    .forUpdate()
    .executeTakeFirst();

  if (!inventoryExecution || inventoryExecution.executionType !== "GOODS_RECEIPT") {
    return err(new InvalidStatusError(input.id));
  }

  const nextStatus = inventoryExecutionLifecycle.tryTransition(inventoryExecution.status, "cancel");
  if (!nextStatus) {
    return err(new InvalidStatusError(input.id));
  }

  const cancelledInventoryExecution = await db
    .updateTable("InventoryExecution")
    .set({ status: nextStatus })
    .where("id", "=", inventoryExecution.id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ inventoryExecution: cancelledInventoryExecution });
}
