// ============================================
// NOTIFIER - API Client
// Replaces LocalStorage Store with real API calls
// ============================================

const Api = {
    // Base URL from app config, fallback to /notifier/api
    get baseUrl() {
        return (window.__APP_CONFIG__?.apiBase) || '/notifier/api';
    },

    /**
     * Core request wrapper with error handling
     */
    async request(method, endpoint, data = null) {
        const url = this.baseUrl + endpoint;
        const options = {
            method,
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            credentials: 'same-origin'
        };

        if (data && method !== 'GET') {
            options.body = JSON.stringify(data);
        }

        try {
            const response = await fetch(url, options);

            // Handle 401 - redirect to login
            if (response.status === 401) {
                window.location.href = '/notifier/login/';
                throw new Error('Session expired');
            }

            const responseClone = response.clone();
            let json = null;
            try {
                json = await response.json();
            } catch (parseError) {
                const text = await responseClone.text();
                const snippet = text ? text.slice(0, 200) : response.statusText;
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${snippet}`);
                }
                throw new Error(`Invalid JSON response: ${snippet}`);
            }

            // Handle API errors
            if (!response.ok || json.success === false) {
                const errorMsg = json.error?.message || json.error || 'Request failed';
                throw new Error(errorMsg);
            }

            return json;
        } catch (error) {
            // Re-throw with better context
            if (error.message === 'Session expired') throw error;
            if (error.name === 'TypeError') {
                throw new Error('Network error - please check your connection');
            }
            throw error;
        }
    },

    // ===== CATEGORIES =====

    async getCategories() {
        const result = await this.request('GET', '/categories');
        return result.data || [];
    },

    async getCategory(id) {
        const result = await this.request('GET', `/categories/${id}`);
        return result.data;
    },

    async createCategory(data) {
        const result = await this.request('POST', '/categories', data);
        return { id: result.id, ...data };
    },

    async updateCategory(id, data) {
        await this.request('PUT', `/categories/${id}`, data);
        return { id, ...data };
    },

    async deleteCategory(id) {
        await this.request('DELETE', `/categories/${id}`);
        return true;
    },

    // ===== NOTIFICATIONS =====

    async getNotifications(params = {}) {
        const query = new URLSearchParams();
        if (params.search) query.set('search', params.search);
        if (params.category_id) query.set('category_id', params.category_id);
        if (params.status) query.set('status', params.status);

        const queryStr = query.toString();
        const endpoint = '/notifications' + (queryStr ? '?' + queryStr : '');
        const result = await this.request('GET', endpoint);
        return result.data || [];
    },

    async getNotification(id) {
        const result = await this.request('GET', `/notifications/${id}`);
        return result.data;
    },

    async createNotification(data) {
        const result = await this.request('POST', '/notifications', data);
        return { id: result.id, ...data };
    },

    async updateNotification(id, data) {
        await this.request('PUT', `/notifications/${id}`, data);
        return { id, ...data };
    },

    async deleteNotification(id) {
        await this.request('DELETE', `/notifications/${id}`);
        return true;
    },

    async pauseNotification(id) {
        await this.request('POST', `/notifications/${id}/pause`);
        return { id, status: 'paused' };
    },

    async resumeNotification(id) {
        await this.request('POST', `/notifications/${id}/resume`);
        return { id, status: 'active' };
    },

    async testNotification(id) {
        const result = await this.request('POST', `/notifications/${id}/test`);
        return result;
    },

    // ===== PREVIEW =====

    async previewSchedule(data) {
        const result = await this.request('POST', '/preview', data);
        return {
            dates: result.dates || [],
            dates_display: result.dates_display || []
        };
    },

    // ===== UPLOAD =====

    async uploadImage(file) {
        const formData = new FormData();
        formData.append('image', file);

        const response = await fetch(this.baseUrl + '/upload', {
            method: 'POST',
            body: formData,
            credentials: 'same-origin'
        });

        if (response.status === 401) {
            window.location.href = '/notifier/login/';
            throw new Error('Session expired');
        }

        const json = await response.json();
        if (!response.ok || json.success === false) {
            throw new Error(json.error?.message || json.error || 'Upload failed');
        }

        return json.data || json;
    },

    // ===== HISTORY =====

    async getHistory(page = 1, limit = 20) {
        const result = await this.request('GET', `/history?page=${page}&limit=${limit}`);
        return {
            history: result.data || [],
            page: result.page || page,
            limit: result.limit || limit
        };
    },

    // ===== JOBS (Failed/Pending) =====

    async getJobs(status = null) {
        const endpoint = status ? `/jobs?status=${status}` : '/jobs';
        const result = await this.request('GET', endpoint);
        return result.data || [];
    },

    async getFailedJobs() {
        return this.getJobs('failed');
    },

    async getPendingJobs() {
        return this.getJobs('pending,retrying');
    },

    async retryJob(jobId) {
        const result = await this.request('POST', `/jobs/${jobId}/retry`);
        return result;
    }
};

// ===== STORE COMPATIBILITY LAYER =====
// This provides backward compatibility with existing code using Store.*
// Will be removed once all pages are fully migrated to Api.*

const Store = {
    _categories: null,
    _notifications: null,
    _history: null,

    // Initialize - now a no-op since we use API
    init() {
        // No longer needed - data comes from API
    },

    // Auth - now handled server-side
    isAuthenticated() {
        // Always true if we reach this point (PHP redirects if not authed)
        return true;
    },
    login(password) {
        // Handled by server-side PHP
        console.warn('Store.login() is deprecated - use server-side auth');
        return false;
    },
    logout() {
        window.location.href = '/notifier/logout/';
    },

    // Categories - async wrappers (for gradual migration)
    getCategories() {
        console.warn('Store.getCategories() is deprecated - use Api.getCategories()');
        return this._categories || [];
    },
    async loadCategories() {
        this._categories = await Api.getCategories();
        return this._categories;
    },
    async addCategory(category) {
        return Api.createCategory(category);
    },
    async updateCategory(id, updates) {
        return Api.updateCategory(id, updates);
    },
    async deleteCategory(id) {
        return Api.deleteCategory(id);
    },

    // Notifications - async wrappers
    getNotifications() {
        console.warn('Store.getNotifications() is deprecated - use Api.getNotifications()');
        return this._notifications || [];
    },
    getNotification(id) {
        console.warn('Store.getNotification() is deprecated - use Api.getNotification()');
        return (this._notifications || []).find(n => n.id === parseInt(id));
    },
    async loadNotifications(params = {}) {
        this._notifications = await Api.getNotifications(params);
        return this._notifications;
    },
    async addNotification(notification) {
        return Api.createNotification(notification);
    },
    async updateNotification(id, updates) {
        return Api.updateNotification(id, updates);
    },
    async deleteNotification(id) {
        return Api.deleteNotification(id);
    },
    async toggleNotificationStatus(id) {
        const notification = this.getNotification(id);
        if (notification) {
            if (notification.status === 'active') {
                return Api.pauseNotification(id);
            } else {
                return Api.resumeNotification(id);
            }
        }
        return null;
    },

    // History - async wrappers
    getHistory() {
        console.warn('Store.getHistory() is deprecated - use Api.getHistory()');
        return this._history || [];
    },
    async loadHistory(page = 1, limit = 20) {
        const result = await Api.getHistory(page, limit);
        this._history = result.history;
        return result;
    }
};

// Export globally
window.Api = Api;
window.Store = Store;
