/**
 * Service für Drag-and-Drop Reordering von Bildern
 */
class ReorderService {
    
    /**
     * Internal HTTP request helper
     * @param {string} url - API endpoint URL
     * @param {string} method - HTTP method (GET, POST, PUT, DELETE)
     * @param {Object} data - Request body data
     * @returns {Promise<Object>} API response
     */
    async makeRequest(url, method = 'GET', data = null) {
        const options = {
            method,
            headers: {
                'Content-Type': 'application/json',
            },
        };

        if (data) {
            options.body = JSON.stringify(data);
        }

        const response = await fetch(url, options);
        
        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`HTTP ${response.status}: ${errorText}`);
        }

        return await response.json();
    }
    
    /**
     * Reorder images within a group
     * @param {string} groupId - The group ID
     * @param {number[]} imageIds - Array of image IDs in new order
     * @returns {Promise<Object>} API response with success status
     */
    async updateImageOrder(groupId, imageIds) {
        if (!groupId) {
            throw new Error('Group ID is required');
        }
        
        if (!Array.isArray(imageIds) || imageIds.length === 0) {
            throw new Error('Image IDs array is required and cannot be empty');
        }

        try {
            const response = await this.makeRequest(`/api/groups/${groupId}/reorder`, 'PUT', {
                imageIds: imageIds
            });

            if (!response.success) {
                throw new Error(response.message || 'Failed to update image order');
            }

            return response;
        } catch (error) {
            console.error('[ReorderService] Error updating image order:', error);
            throw error;
        }
    }

    /**
     * Validate that all image IDs belong to the specified group
     * @param {Object[]} images - Array of image objects from the group
     * @param {number[]} imageIds - Array of image IDs to validate
     * @returns {boolean} True if all IDs are valid
     */
    validateImageIds(images, imageIds) {
        if (!Array.isArray(images) || !Array.isArray(imageIds)) {
            return false;
        }

        const availableIds = images.map(img => img.id);
        return imageIds.every(id => availableIds.includes(id));
    }

    /**
     * Extract image IDs from image objects array
     * @param {Object[]} images - Array of image objects
     * @returns {number[]} Array of image IDs
     */
    extractImageIds(images) {
        if (!Array.isArray(images)) {
            return [];
        }
        
        return images.map(img => img.id).filter(id => typeof id === 'number');
    }

    /**
     * Reorder array based on new indices
     * @param {Array} items - Original array to reorder
     * @param {number} startIndex - Original index
     * @param {number} endIndex - New index
     * @returns {Array} Reordered array
     */
    reorderArray(items, startIndex, endIndex) {
        const result = Array.from(items);
        const [removed] = result.splice(startIndex, 1);
        result.splice(endIndex, 0, removed);
        return result;
    }
}

// Create and export service instance
const reorderService = new ReorderService();

export default reorderService;

// Named exports for easier testing  
export const updateImageOrder = (groupId, imageIds) => reorderService.updateImageOrder(groupId, imageIds);
export const validateImageIds = (images, imageIds) => reorderService.validateImageIds(images, imageIds);
export const extractImageIds = (images) => reorderService.extractImageIds(images);
export const reorderArray = (items, startIndex, endIndex) => reorderService.reorderArray(items, startIndex, endIndex);