/**
 * AniWorld - API Client Module
 *
 * HTTP request wrapper with automatic authentication
 * and error handling.
 *
 * Dependencies: constants.js, auth.js
 */

var AniWorld = window.AniWorld || {};

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

    /**
     * Make an authenticated HTTP request
     * Automatically includes Authorization header and handles 401 responses
     * 
     * @param {string} url - The API endpoint URL
     * @param {Object} options - Fetch options (method, headers, body, etc.)
     * @returns {Promise<Response|null>} The fetch response or null if auth failed
     */
    async function request(url, options) {
        options = options || {};
        
        // Get JWT token from localStorage
        const token = AniWorld.Auth.getToken();
        
        // Check if token exists
        if (!token) {
            window.location.href = '/login';
            return null;
        }
        
        // Build request options with auth header
        const requestOptions = {
            credentials: 'same-origin',
            ...options,
            headers: {
                'Authorization': 'Bearer ' + token,
                ...options.headers
            }
        };

        // Add Content-Type for JSON body if not already set
        if (options.body && typeof options.body === 'string' && !requestOptions.headers['Content-Type']) {
            requestOptions.headers['Content-Type'] = 'application/json';
        }

        const response = await fetch(url, requestOptions);

        if (response.status === 401) {
            // Token is invalid or expired, clear it and redirect to login
            AniWorld.Auth.removeToken();
            window.location.href = '/login';
            return null;
        }

        return response;
    }

    /**
     * Make a GET request
     * @param {string} url - The API endpoint URL
     * @param {Object} headers - Additional headers
     * @returns {Promise<Response|null>}
     */
    async function get(url, headers) {
        return request(url, { method: 'GET', headers: headers });
    }

    /**
     * Make a POST request with JSON body
     * @param {string} url - The API endpoint URL
     * @param {Object} data - The data to send
     * @param {Object} headers - Additional headers
     * @returns {Promise<Response|null>}
     */
    async function post(url, data, headers) {
        return request(url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', ...headers },
            body: JSON.stringify(data)
        });
    }

    /**
     * Make a DELETE request
     * @param {string} url - The API endpoint URL
     * @param {Object} headers - Additional headers
     * @returns {Promise<Response|null>}
     */
    async function del(url, headers) {
        return request(url, { method: 'DELETE', headers: headers });
    }

    /**
     * Make a PUT request with JSON body
     * @param {string} url - The API endpoint URL
     * @param {Object} data - The data to send
     * @param {Object} headers - Additional headers
     * @returns {Promise<Response|null>}
     */
    async function put(url, data, headers) {
        return request(url, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json', ...headers },
            body: JSON.stringify(data)
        });
    }

    // Public API
    return {
        request: request,
        get: get,
        post: post,
        delete: del,
        put: put
    };
})();
