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

export interface ReactivateStorageLocationInput {
  id: string;
}

/**
 * Function: reactivateStorageLocation
 *
 * Transitions a storage location from INACTIVE back to ACTIVE status.
 * The parent warehouse must still be in ACTIVE status.
 */
export async function run(
  db: Transaction,
  input: ReactivateStorageLocationInput,
  _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 INACTIVE
  if (location.status !== "INACTIVE") {
    return err(new StorageLocationNotInactiveError(id));
  }

  // 3. Validate parent warehouse is ACTIVE
  const warehouse = await db
    .selectFrom("Warehouse")
    .selectAll()
    .where("id", "=", location.warehouseId)
    .executeTakeFirst();

  if (warehouse?.status !== "ACTIVE") {
    return err(new WarehouseInactiveError(location.warehouseId));
  }

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

  return ok({ storageLocation: reactivatedLocation });
}
