import { ok, executeTransition, type CommandContext } from "@tailor-platform/erp-kit/core";
import { storageLocationLifecycle } from "../db/storageLocation.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  StorageLocationNotFoundError,
  StorageLocationNotActiveError,
} from "../lib/errors.generated";

export interface DeactivateStorageLocationInput {
  id: string;
}

/**
 * Function: deactivateStorageLocation
 *
 * Transitions a storage location from ACTIVE to INACTIVE status.
 * Deactivation does NOT cascade to child bins.
 */
export async function run(
  db: Transaction,
  input: DeactivateStorageLocationInput,
  _ctx: CommandContext,
) {
  const result = await executeTransition({
    db,
    tableName: "StorageLocation",
    statusField: "status",
    id: input.id,
    transition: "deactivate",
    lifecycle: storageLocationLifecycle,
    errors: {
      notFound: StorageLocationNotFoundError,
      invalidTransition: StorageLocationNotActiveError,
    },
  });
  if (!result.ok) return result;
  return ok({ storageLocation: result.value });
}
