import getDraggablesInsideDroppable from "../../get-draggables-inside-droppable";
import { warning } from "../../../dev-warning";

function checkIndexes(insideDestination) {
  // no point running if there are 1 or less items
  if (insideDestination.length <= 1) {
    return;
  }
  const indexes = insideDestination.map((d) => d.descriptor.index);
  const errors = {};
  for (let i = 1; i < indexes.length; i++) {
    const current = indexes[i];
    const previous = indexes[i - 1];

    // this will be an error if:
    // 1. index is not consecutive
    // 2. index is duplicated (which is true if #1 is not passed)
    if (current !== previous + 1) {
      errors[current] = true;
    }
  }
  if (!Object.keys(errors).length) {
    return;
  }
  const formatted = indexes
    .map((index) => {
      const hasError = Boolean(errors[index]);
      return hasError ? `[🔥${index}]` : `${index}`;
    })
    .join(", ");
  warning(`
    Detected non-consecutive <Draggable /> indexes.

    (This can cause unexpected bugs)

    ${formatted}
  `);
}

export default function validateDimensions(critical, dimensions) {
  // wrapping entire block for better minification
  if (import.meta.env.DEV) {
    const insideDestination = getDraggablesInsideDroppable(critical.droppable.id, dimensions.draggables);
    checkIndexes(insideDestination);
  }
}
