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

export interface CancelInventoryCountInput {
  inventoryCountId: string;
}

/**
 * Function: cancelInventoryCount
 *
 * Cancels an inventory count in PLANNED or IN_PROGRESS status.
 * Unfreezes stock if frozen and discards all count line data.
 */
export async function run(db: Transaction, input: CancelInventoryCountInput, _ctx: CommandContext) {
  const { inventoryCountId } = input;

  // 1. Fetch count
  const count = await db
    .selectFrom("InventoryCount")
    .selectAll()
    .where("id", "=", inventoryCountId)
    .forUpdate()
    .executeTakeFirst();

  if (!count) {
    return err(new CountNotFoundError(inventoryCountId));
  }

  // 2. Validate status
  if (count.status === "COMPLETED") {
    return err(new CountAlreadyCompletedError(inventoryCountId));
  }

  if (count.status === "CANCELLED") {
    return err(new CountAlreadyCancelledError(inventoryCountId));
  }

  // 3. Delete all count lines
  await db
    .deleteFrom("InventoryCountLine")
    .where("inventoryCountId", "=", inventoryCountId)
    .execute();

  // 4. Update status to CANCELLED and unfreeze
  const updatedCount = await db
    .updateTable("InventoryCount")
    .set({
      status: "CANCELLED",
      isFrozen: false,
      updatedAt: new Date(),
    })
    .where("id", "=", inventoryCountId)
    .returningAll()
    .executeTakeFirst();

  return ok({ inventoryCount: updatedCount! });
}
