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

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 { id } = input;

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

  if (!location) {
    return err(new StorageLocationNotFoundError(id));
  }

  // 2. Check status is ACTIVE
  if (location.status !== "ACTIVE") {
    return err(new StorageLocationNotActiveError(id));
  }

  // 3. Update status to INACTIVE
  const deactivatedLocation = await db
    .updateTable("StorageLocation")
    .set({ status: "INACTIVE", updatedAt: new Date() })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ storageLocation: deactivatedLocation });
}
