import { Controller } from '@hotwired/stimulus';

/* Historique : export Excel par session, changement de statut, suppression. */
export default class extends Controller {
    static targets = ['empty', 'listWrapper', 'list', 'card', 'count'];

    async export(event) {
        const { id } = event.params;
        const res = await fetch('/api/export/xlsx', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ sessionId: id }),
        });
        if (!res.ok) return;
        const blob = await res.blob();
        const objUrl = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = objUrl;
        a.download = 'scan-vehicules.xlsx';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        setTimeout(() => URL.revokeObjectURL(objUrl), 1000);
    }

    async setStatus(event) {
        const { id, status } = event.params;
        const res = await fetch(`/api/history/${encodeURIComponent(id)}/status`, {
            method: 'PATCH',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ status }),
        });
        if (!res.ok) {
            const data = await res.json().catch(() => null);
            window.alert(data?.error || 'Échec du changement de statut.');
            return;
        }
        window.location.reload();
    }

    async delete(event) {
        const { id } = event.params;
        if (!window.confirm('Supprimer cette session ?')) return;
        await fetch(`/api/history?id=${encodeURIComponent(id)}`, { method: 'DELETE' });
        const card = this.cardTargets.find((c) => c.dataset.id === id);
        card?.remove();
        this.refreshState();
    }

    async clearAll() {
        if (!window.confirm('Supprimer tout l\'historique ? Cette action est irréversible.')) return;
        await fetch('/api/history', { method: 'DELETE' });
        this.cardTargets.forEach((c) => c.remove());
        this.refreshState();
    }

    refreshState() {
        const remaining = this.cardTargets.length;
        this.countTarget.textContent = String(remaining);
        if (remaining === 0) {
            this.listWrapperTarget.classList.add('hidden');
            this.emptyTarget.classList.remove('hidden');
        }
    }
}
