// Settings → Update fixture catalog (KL-142).
//
// Posts to /api/fixtures/catalog/refresh, watches the response for the
// up_to_date / new fixture-count delta, and surfaces the result via:
//   - a small inline status string in the setting-row (live during the
//     fetch so the user knows we're working)
//   - a one-shot toast on completion (success, no-op, or error)
//
// Synchronous on the backend: a typical refresh is 2-5 seconds. We
// don't stream progress yet — Step 4 of the ticket adds the CDN upload
// pipeline that backs this; until then the button just hits a 502 in
// dev (the backend short-circuits on RefreshError gracefully).

import {pushToast} from './toasts.js';

function storeDefinition() {
    return {
        // 'idle' | 'busy' | 'done' — drives button-disabled + status copy.
        state: 'idle',
        // Snapshot of the last successful run so we can re-render
        // "Last refreshed: 2 min ago, 2528 fixtures" alongside the button.
        lastResult: null,
        errorText: '',

        get isBusy() { return this.state === 'busy'; },

        get statusText() {
            if (this.state === 'busy') return 'Checking for updates…';
            if (this.errorText) return this.errorText;
            if (this.lastResult) {
                const r = this.lastResult;
                if (r.up_to_date) {
                    return `Already up to date (${r.fixture_count} fixtures).`;
                }
                const delta = r.fixture_count - (r.previous_count || 0);
                const sign = delta > 0 ? '+' : '';
                return `Updated to ${r.fixture_count} fixtures (${sign}${delta} from last refresh).`;
            }
            return 'Pull the latest fixture profiles from the Conductør CDN.';
        },

        async refresh() {
            if (this.state === 'busy') return;
            this.state = 'busy';
            this.errorText = '';
            try {
                const r = await fetch('/api/fixtures/catalog/refresh', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                });
                const body = await r.json().catch(() => ({}));
                if (!r.ok || !body.ok) {
                    const msg = body.error || `Refresh failed (${r.status}).`;
                    this.errorText = msg;
                    pushToast({
                        key: 'catalog-refresh-error',
                        level: 'error',
                        title: 'Catalog refresh failed',
                        detail: msg,
                    });
                    return;
                }
                this.lastResult = body;
                // The response includes a fresh `templates` snapshot —
                // hand it to the fixtures store so the Add Fixture
                // dropdown reflects the new catalog without a separate
                // GET round-trip.
                const fxStore = window.Alpine?.store?.('fixtures');
                if (fxStore && Array.isArray(body.templates)) {
                    fxStore.catalogTemplates = body.templates;
                }
                if (body.up_to_date) {
                    pushToast({
                        key: 'catalog-refresh-result',
                        level: 'info',
                        title: 'Catalog already up to date',
                        detail: `${body.fixture_count} fixtures — no changes since last refresh.`,
                    });
                } else {
                    const prev = body.previous_count || 0;
                    const delta = body.fixture_count - prev;
                    const summary = delta > 0
                        ? `+${delta} new fixtures (now ${body.fixture_count} total).`
                        : `${body.fixture_count} fixtures total.`;
                    pushToast({
                        key: 'catalog-refresh-result',
                        level: 'info',
                        title: 'Fixture catalog updated',
                        detail: summary,
                    });
                }
            } catch (e) {
                const msg = `Network error: ${e.message || e}`;
                this.errorText = msg;
                pushToast({
                    key: 'catalog-refresh-error',
                    level: 'error',
                    title: 'Catalog refresh failed',
                    detail: msg,
                });
            } finally {
                this.state = this.errorText ? 'idle' : 'done';
            }
        },
    };
}

function ensureStore() {
    if (!window.Alpine) return null;
    if (!window.Alpine.store('catalogRefresh')) {
        window.Alpine.store('catalogRefresh', storeDefinition());
    }
    return window.Alpine.store('catalogRefresh');
}

if (window.Alpine) {
    ensureStore();
} else {
    document.addEventListener('alpine:init', ensureStore);
}

export function initCatalogRefresh() {
    ensureStore();
}
