import { defineStore } from 'pinia';
import { ApiContentSourceRepository } from '../../infrastructure/api/apiContentSourceRepository';

const contentSourceRepository = new ApiContentSourceRepository();

export const useContentSourceStore = defineStore('contentSource', {
    state: () => ({
        // Collection state
        sources: [],
        loadingSources: false,
        sourcesError: null,

        // Current source state
        currentSource: null,
        loadingCurrentSource: false,
        currentSourceError: null,

        // Create/Update state
        saving: false,
        saveError: null,

        // Import/Export state
        importing: false,
        exporting: false,
        importError: null,
        exportError: null,

        // Health check state
        checkingHealth: false,
        checkHealthError: null,

        // Delete state
        deleting: false,
        deleteError: null,
    }),

    getters: {
        getSourceById: (state) => (id) => {
            return state.sources.find(source => source.id === id);
        },

        getSourcesByType: (state) => (scrapingType) => {
            return state.sources.filter(source => source.scrapingType === scrapingType);
        },

        htmlSources: (state) => {
            return state.sources.filter(source => source.scrapingType === 'HTML');
        },

        javascriptSources: (state) => {
            return state.sources.filter(source => source.scrapingType === 'Javascript');
        }
    },

    actions: {
        // Load all sources
        async loadSources() {
            if (this.loadingSources) return;

            this.loadingSources = true;
            this.sourcesError = null;

            try {
                this.sources = await contentSourceRepository.getAll();
            } catch (error) {
                this.sourcesError = error.message;
                console.error('Erreur lors du chargement des sources:', error);
            } finally {
                this.loadingSources = false;
            }
        },

        // Load specific source by ID
        async loadSource(id) {
            if (this.loadingCurrentSource) return;

            this.loadingCurrentSource = true;
            this.currentSourceError = null;

            try {
                this.currentSource = await contentSourceRepository.getById(id);
            } catch (error) {
                this.currentSourceError = error.message;
                console.error('Erreur lors du chargement de la source:', error);
            } finally {
                this.loadingCurrentSource = false;
            }
        },

        // Create new source
        async createSource(sourceData) {
            if (this.saving) return;

            this.saving = true;
            this.saveError = null;

            try {
                const newSource = await contentSourceRepository.create(sourceData);
                this.sources.push(newSource);
                return newSource;
            } catch (error) {
                this.saveError = error.message;
                console.error('Erreur lors de la création de la source:', error);
                throw error;
            } finally {
                this.saving = false;
            }
        },

        // Update existing source
        async updateSource(id, sourceData) {
            if (this.saving) return;

            this.saving = true;
            this.saveError = null;

            try {
                const updatedSource = await contentSourceRepository.update(id, sourceData);

                // Update in sources array
                const index = this.sources.findIndex(source => source.id === id);
                if (index !== -1) {
                    this.sources[index] = updatedSource;
                }

                // Update current source if it's the same
                if (this.currentSource && this.currentSource.id === id) {
                    this.currentSource = updatedSource;
                }

                return updatedSource;
            } catch (error) {
                this.saveError = error.message;
                console.error('Erreur lors de la mise à jour de la source:', error);
                throw error;
            } finally {
                this.saving = false;
            }
        },

        // Export sources
        async exportSources() {
            if (this.exporting) return;

            this.exporting = true;
            this.exportError = null;

            try {
                return await contentSourceRepository.export();
            } catch (error) {
                this.exportError = error.message;
                console.error('Erreur lors de l\'export:', error);
                throw error;
            } finally {
                this.exporting = false;
            }
        },

        // Import sources
        async importSources(sourcesData) {
            if (this.importing) return;

            this.importing = true;
            this.importError = null;

            try {
                await contentSourceRepository.import(sourcesData);
                // Reload sources after import
                await this.loadSources();
            } catch (error) {
                this.importError = error.message;
                console.error('Erreur lors de l\'import:', error);
                throw error;
            } finally {
                this.importing = false;
            }
        },

        // Delete a source
        async deleteSource(id) {
            if (this.deleting) return;

            this.deleting = true;
            this.deleteError = null;

            try {
                await contentSourceRepository.delete(id);
                this.sources = this.sources.filter(source => source.id !== id);
                if (this.currentSource && this.currentSource.id === id) {
                    this.currentSource = null;
                }
            } catch (error) {
                this.deleteError = error.message;
                console.error('Erreur lors de la suppression de la source:', error);
                throw error;
            } finally {
                this.deleting = false;
            }
        },

        // Clear current source
        clearCurrentSource() {
            this.currentSource = null;
            this.currentSourceError = null;
        },

        // Check all scrapers health
        async checkAllHealth() {
            if (this.checkingHealth) return;

            this.checkingHealth = true;
            this.checkHealthError = null;

            try {
                await contentSourceRepository.checkAllHealth();
            } catch (error) {
                this.checkHealthError = error.message;
                console.error('Erreur lors du health check:', error);
                throw error;
            } finally {
                this.checkingHealth = false;
            }
        },

        // Update health status of a single source (called from Mercure)
        updateSourceHealth(sourceId, status, error = null) {
            const index = this.sources.findIndex(s => s.id === sourceId);
            if (index !== -1) {
                this.sources[index] = {
                    ...this.sources[index],
                    healthStatus: status,
                    healthLastError: error,
                };
            }
        },

        // Clear errors
        clearErrors() {
            this.sourcesError = null;
            this.currentSourceError = null;
            this.saveError = null;
            this.importError = null;
            this.exportError = null;
            this.checkHealthError = null;
        }
    }
});
