import {TaggedUser} from '@interfaces/taggedUsers';

export const detectDeletedTags = ({
  oldText,
  newText,
  currentTags,
  selectionRange,
}: {
  oldText: string;
  newText: string;
  currentTags: TaggedUser[];
  selectionRange: {start: number; end: number};
}): TaggedUser[] => {
  const deletedTags: TaggedUser[] = [];

  // If there's a selection, check if any tags are within the selection range
  if (selectionRange.start !== selectionRange.end) {
    currentTags.forEach(tag => {
      const tagStart = tag.start;
      const tagEnd = tag.start + tag.length;

      // Check if tag is completely or partially within selection
      if (
        (selectionRange.start <= tagStart && selectionRange.end >= tagEnd) || // Tag completely selected
        (selectionRange.start < tagEnd && selectionRange.end > tagStart) // Tag partially selected
      ) {
        deletedTags.push(tag);
      }
    });
  } else {
    // Single cursor position - check if we're deleting within a tag
    const cursorPosition = selectionRange.start;
    const deletedLength = oldText.length - newText.length;

    if (deletedLength > 0) {
      currentTags.forEach(tag => {
        const tagStart = tag.start;
        const tagEnd = tag.start + tag.length;

        // Check if deletion affects this tag
        if (cursorPosition >= tagStart && cursorPosition <= tagEnd) {
          deletedTags.push(tag);
        }
      });
    }
  }

  return deletedTags;
};

export const shouldHandleTagDeletionManually = ({
  oldText,
  newText,
  selectionRange,
  currentPosition,
}: {
  oldText: string;
  newText: string;
  selectionRange: Nullable<{start: number; end: number}>;
  currentPosition: Nullable<number>;
}): boolean => {
  const hasSelection = !!selectionRange;
  const currentPos = currentPosition ?? 0;
  const isTextShorter = newText.length < oldText.length;
  const isCursorNotAtEnd = currentPos > 0 && currentPos < oldText.length;

  return hasSelection || (isCursorNotAtEnd && isTextShorter);
};
