package reorder

import (
	"github.com/tech/sendico/pkg/merrors"
	"github.com/tech/sendico/pkg/model"
)

// IndexableRefs reorders a slice of IndexableRef items
// Returns the reordered slice with updated indices, or an error if indices are invalid
func IndexableRefs(items []model.IndexableRef, oldIndex, newIndex int) ([]model.IndexableRef, error) {
	// Find the item to reorder
	targetIndex := -1
	for i, item := range items {
		if item.Index == oldIndex {
			targetIndex = i
			break
		}
	}
	if targetIndex == -1 {
		return nil, merrors.InvalidArgument("Item not found at specified index", "oldIndex")
	}

	// Validate new index bounds
	if newIndex < 0 || newIndex >= len(items) {
		return nil, merrors.InvalidArgument("Invalid new index for reorder", "newIndex")
	}

	// Remove the item from its current position
	itemToMove := items[targetIndex]
	items = append(items[:targetIndex], items[targetIndex+1:]...)

	// Insert the item at the new position
	items = append(items[:newIndex],
		append([]model.IndexableRef{itemToMove}, items[newIndex:]...)...)

	// Update indices
	for i := range items {
		items[i].Index = i
	}

	return items, nil
}
