/**
 * AniWorld - Queue API Module
 *
 * Handles API requests for the download queue.
 *
 * Dependencies: constants.js, api-client.js
 */

var AniWorld = window.AniWorld || {};

AniWorld.QueueAPI = (function() {
    'use strict';

    const API = AniWorld.Constants.API;

    /**
     * Load queue data from server
     * @returns {Promise<Object>} Queue data
     */
    async function loadQueueData() {
        try {
            const response = await AniWorld.ApiClient.get(API.QUEUE_STATUS);
            if (!response) {
                return null;
            }

            const data = await response.json();

            // API returns nested structure with 'status' and 'statistics'
            // Transform it to the expected flat structure
            return {
                ...data.status,
                statistics: data.statistics
            };
        } catch (error) {
            console.error('Error loading queue data:', error);
            return null;
        }
    }

    /**
     * Start queue processing
     * @returns {Promise<Object>} Response data
     */
    async function startQueue() {
        try {
            const response = await AniWorld.ApiClient.post(API.QUEUE_START, {});
            if (!response) return null;
            return await response.json();
        } catch (error) {
            console.error('Error starting queue:', error);
            throw error;
        }
    }

    /**
     * Stop queue processing
     * @returns {Promise<Object>} Response data
     */
    async function stopQueue() {
        try {
            const response = await AniWorld.ApiClient.post(API.QUEUE_STOP, {});
            if (!response) return null;
            return await response.json();
        } catch (error) {
            console.error('Error stopping queue:', error);
            throw error;
        }
    }

    /**
     * Remove item from queue
     * @param {string} downloadId - Download item ID
     * @returns {Promise<boolean>} Success status
     */
    async function removeFromQueue(downloadId) {
        try {
            const response = await AniWorld.ApiClient.delete(API.QUEUE_REMOVE + '/' + downloadId);
            if (!response) return false;
            return response.status === 204;
        } catch (error) {
            console.error('Error removing from queue:', error);
            throw error;
        }
    }

    /**
     * Retry failed downloads
     * @param {Array<string>} itemIds - Array of download item IDs
     * @returns {Promise<Object>} Response data
     */
    async function retryDownloads(itemIds) {
        try {
            const response = await AniWorld.ApiClient.post(API.QUEUE_RETRY, { item_ids: itemIds });
            if (!response) return null;
            return await response.json();
        } catch (error) {
            console.error('Error retrying downloads:', error);
            throw error;
        }
    }

    /**
     * Clear completed downloads
     * @returns {Promise<Object>} Response data
     */
    async function clearCompleted() {
        try {
            const response = await AniWorld.ApiClient.delete(API.QUEUE_COMPLETED);
            if (!response) return null;
            return await response.json();
        } catch (error) {
            console.error('Error clearing completed:', error);
            throw error;
        }
    }

    /**
     * Clear failed downloads
     * @returns {Promise<Object>} Response data
     */
    async function clearFailed() {
        try {
            const response = await AniWorld.ApiClient.delete(API.QUEUE_FAILED);
            if (!response) return null;
            return await response.json();
        } catch (error) {
            console.error('Error clearing failed:', error);
            throw error;
        }
    }

    /**
     * Clear pending downloads
     * @returns {Promise<Object>} Response data
     */
    async function clearPending() {
        try {
            const response = await AniWorld.ApiClient.delete(API.QUEUE_PENDING);
            if (!response) return null;
            return await response.json();
        } catch (error) {
            console.error('Error clearing pending:', error);
            throw error;
        }
    }

    // Public API
    return {
        loadQueueData: loadQueueData,
        startQueue: startQueue,
        stopQueue: stopQueue,
        removeFromQueue: removeFromQueue,
        retryDownloads: retryDownloads,
        clearCompleted: clearCompleted,
        clearFailed: clearFailed,
        clearPending: clearPending
    };
})();
