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

export interface CancelStockMovementInput {
  id: string;
}

/**
 * Function: cancelStockMovement
 *
 * Cancels a stock movement in DRAFT or CONFIRMED status.
 * Movements already executed (DONE) cannot be cancelled.
 */
export async function run(db: Transaction, input: CancelStockMovementInput, _ctx: CommandContext) {
  const { id } = input;

  // 1. Check movement exists
  const movement = await db
    .selectFrom("StockMovement")
    .selectAll()
    .where("id", "=", id)
    .forUpdate()
    .executeTakeFirst();

  if (!movement) {
    return err(new StockMovementNotFoundError(id));
  }

  // 2. Cannot cancel DONE
  if (movement.status === "DONE") {
    return err(new StockMovementAlreadyDoneError(id));
  }

  // 3. Cannot cancel already CANCELLED
  if (movement.status === "CANCELLED") {
    return err(new StockMovementAlreadyCancelledError(id));
  }

  // 4. Update status to CANCELLED
  const cancelled = await db
    .updateTable("StockMovement")
    .set({
      status: "CANCELLED",
      updatedAt: new Date(),
    })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirst();

  return ok({ stockMovement: cancelled! });
}
