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

const jobRepository = new ApiJobRepository();

export const useActivityStore = defineStore('activity', {
    state: () => ({
        jobs: [],
        loading: false,
        error: null,
        // Pagination
        currentPage: 1,
        totalPages: 0,
        total: 0,
        limit: 20,
        hasNextPage: false,
        hasPreviousPage: false,
        // Filtres
        filter: {
            status: ['pending', 'in_progress'], // Par défaut, ne montrer que les actifs
            sortBy: 'createdAt',
            sortOrder: 'DESC'
        }
    }),

    getters: {
        activeJobs: state => state.jobs.filter(job => job.isActive()),
        completedJobs: state => state.jobs.filter(job => job.isCompleted()),
        failedJobs: state => state.jobs.filter(job => job.hasError()),
        isLoading: state => state.loading,
        hasError: state => !!state.error,
        // Getters pour la pagination
        paginationInfo: state => ({
            currentPage: state.currentPage,
            totalPages: state.totalPages,
            total: state.total,
            limit: state.limit,
            hasNextPage: state.hasNextPage,
            hasPreviousPage: state.hasPreviousPage
        })
    },

    actions: {
        /**
         * Charge la liste des jobs selon les filtres actuels
         * @param {number} page - Numéro de page optionnel
         */
        async loadJobs(page = null) {
            this.loading = true;
            this.error = null;

            try {
                const options = {
                    page: page || this.currentPage,
                    limit: this.limit,
                    sortBy: this.filter.sortBy,
                    sortOrder: this.filter.sortOrder,
                    status: this.filter.status
                };

                const jobCollection = await jobRepository.getJobs(options);

                // Mettre à jour les données
                this.jobs = jobCollection.items;
                this.currentPage = jobCollection.page;
                this.total = jobCollection.total;
                this.hasNextPage = jobCollection.hasNextPage;
                this.hasPreviousPage = jobCollection.hasPreviousPage;

                // Calculer le nombre total de pages
                this.totalPages = Math.ceil(this.total / this.limit);

                console.log('Store updated with:', {
                    jobs: this.jobs.length,
                    currentPage: this.currentPage,
                    total: this.total,
                    limit: this.limit,
                    totalPages: this.totalPages,
                    hasNextPage: this.hasNextPage,
                    hasPreviousPage: this.hasPreviousPage
                });
            } catch (error) {
                this.error = error.message;
                console.error('Error loading jobs:', error);
            } finally {
                this.loading = false;
            }
        },

        /**
         * Va à une page spécifique
         * @param {number} page
         */
        async goToPage(page) {
            if (page >= 1 && page <= this.totalPages && page !== this.currentPage) {
                this.currentPage = page;
                await this.loadJobs(page);
            }
        },

        /**
         * Met à jour les filtres et recharge la liste
         * @param {Object} filter
         */
        async updateFilter(filter) {
            this.filter = { ...this.filter, ...filter };
            this.currentPage = 1; // Retourner à la première page lors du changement de filtre
            await this.loadJobs(1);
        },

        /**
         * Met à jour la limite par page
         * @param {number} limit
         */
        async updateLimit(limit) {
            this.limit = limit;
            this.currentPage = 1; // Retourner à la première page
            await this.loadJobs(1);
        },

        /**
         * Supprime un job par son ID
         * @param {string} id
         */
        async deleteJob(id) {
            this.loading = true;
            this.error = null;

            try {
                await jobRepository.deleteJob(id);
                // Supprimer le job de la liste locale
                this.jobs = this.jobs.filter(job => job.id !== id);
                // Recharger la page courante pour avoir les bons totaux
                await this.loadJobs(this.currentPage);
            } catch (error) {
                this.error = error.message;
                console.error('Error deleting job:', error);
            } finally {
                this.loading = false;
            }
        },

        /**
         * Supprime tous les jobs correspondant aux critères
         * @param {Object} criteria
         */
        async deleteJobs(criteria = {}) {
            this.loading = true;
            this.error = null;

            try {
                const deleted = await jobRepository.deleteJobs(criteria);
                // Recharger la liste après suppression
                await this.loadJobs(this.currentPage);
                return deleted;
            } catch (error) {
                this.error = error.message;
                console.error('Error deleting jobs:', error);
            } finally {
                this.loading = false;
            }
        },

        /**
         * Supprime tous les jobs terminés
         */
        async deleteCompletedJobs() {
            return this.deleteJobs({ status: ['COMPLETED'] });
        },

        /**
         * Supprime tous les jobs en erreur
         */
        async deleteFailedJobs() {
            return this.deleteJobs({ status: ['ERROR'] });
        },

        /**
         * Supprime tous les jobs
         */
        async deleteAllJobs() {
            return this.deleteJobs({});
        }
    }
});
