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

const jobRepository = new ApiJobRepository();

// Statuts disponibles par filtre
const STATUS_MAP = {
    failed: ['failed'],
    completed: ['completed'],
    all: ['failed', 'completed'],
};

export const useLogsStore = defineStore('logs', {
    state: () => ({
        logs: [],
        loading: false,
        error: null,
        currentPage: 1,
        totalPages: 0,
        total: 0,
        limit: 50,
        hasNextPage: false,
        hasPreviousPage: false,
        sortBy: 'createdAt',
        sortOrder: 'DESC',
        statusFilter: 'failed', // 'failed' | 'completed' | 'all'
    }),

    getters: {
        isLoading: state => state.loading,
        hasError: state => !!state.error,
    },

    actions: {
        async loadLogs(page = null) {
            this.loading = true;
            this.error = null;

            try {
                const collection = await jobRepository.getJobs({
                    page: page || this.currentPage,
                    limit: this.limit,
                    sortBy: this.sortBy,
                    sortOrder: this.sortOrder,
                    status: STATUS_MAP[this.statusFilter],
                    type: 'scraping_job',
                });

                this.logs = collection.items;
                this.currentPage = collection.page;
                this.total = collection.total;
                this.hasNextPage = collection.hasNextPage;
                this.hasPreviousPage = collection.hasPreviousPage;
                this.totalPages = Math.ceil(this.total / this.limit);
            } catch (error) {
                this.error = error.message;
            } finally {
                this.loading = false;
            }
        },

        async goToPage(page) {
            if (page >= 1 && page <= this.totalPages && page !== this.currentPage) {
                this.currentPage = page;
                await this.loadLogs(page);
            }
        },

        async updateSort(sortBy, sortOrder) {
            this.sortBy = sortBy;
            this.sortOrder = sortOrder;
            this.currentPage = 1;
            await this.loadLogs(1);
        },

        async setStatusFilter(filter) {
            this.statusFilter = filter;
            this.currentPage = 1;
            await this.loadLogs(1);
        },

        async deleteLog(id) {
            try {
                await jobRepository.deleteJob(id);
                this.logs = this.logs.filter(log => log.id !== id);
                this.total = Math.max(0, this.total - 1);
                this.totalPages = Math.ceil(this.total / this.limit);
            } catch (error) {
                this.error = error.message;
            }
        },

        async deleteAllLogs() {
            this.loading = true;
            this.error = null;

            try {
                await jobRepository.deleteJobs({
                    status: STATUS_MAP[this.statusFilter].join(','),
                    type: 'scraping_job',
                });
                await this.loadLogs(1);
            } catch (error) {
                this.error = error.message;
            } finally {
                this.loading = false;
            }
        },
    },
});
