// wwwroot/js/filterdb.js
class FilterCairDB extends Dexie {
    constructor() {
        super('FilterOfflineDB');
        this.version(4).stores({
            customers: 'id, name, standort, email, ansprechpartner',
            stations: 'id, customerId, name, standort',
            filters: 'id, stationId, bezzeichnung, typ',
            outbox: '++id, action, entityId, payload, timestamp'
        });
        this.customers = this.table('customers');
        this.stations = this.table('stations');
        this.filters = this.table('filters');
        this.outbox = this.table('outbox');
    }
}
const db = new FilterCairDB();

window.filterDb = {
    saveAll: async (customersJson) => {
        try {
            const customers = JSON.parse(customersJson);
            await db.customers.clear();
            await db.customers.bulkPut(customers);
            console.log(`IndexedDB: ${customers.length} Kunden gespeichert`);
            return true;
        } catch (err) {
            console.error('saveAll Fehler:', err);
            return false;
        }
    },

    getAll: async () => {
        try {
            const customers = await db.customers.toArray();
            console.log('IndexedDB Inhalt:', customers);
            return JSON.stringify(customers);
        } catch (err) {
            console.error('getAll Fehler:', err);
            return '[]';
        }
    },

    put: async (customerJson) => {
        try {
            const customer = JSON.parse(customerJson);
            await db.customers.put(customer);
            return true;
        } catch (err) {
            console.error('put Fehler:', err);
            return false;
        }
    },

    delete: async (id) => {
        try {
            await db.customers.delete(id);
            return true;
        } catch (err) {
            console.error('delete Fehler:', err);
            return false;
        }
    },

    saveStations: async (customerId, stationsJson) => {
        try {
            const stations = JSON.parse(stationsJson);
            await db.stations.where('customerId').equals(customerId).delete();
            await db.stations.bulkPut(stations);
            console.log(`IndexedDB: ${stations.length} Stationen für Kunde ${customerId} gespeichert`);
            return true;
        } catch (err) {
            console.error('saveStations Fehler:', err);
            return false;
        }
    },

    getStations: async (customerId) => {
        try {
            const stations = await db.stations.where('customerId').equals(customerId).toArray();
            return JSON.stringify(stations);
        } catch (err) {
            console.error('getStations Fehler:', err);
            return '[]';
        }
    },

    saveFilters: async (stationId, filtersJson) => {
        try {
            const filters = JSON.parse(filtersJson);
            await db.filters.where('stationId').equals(stationId).delete();
            await db.filters.bulkPut(filters.map(f => ({
                ...f,
                einbaudatum: f.einbaudatum ? new Date(f.einbaudatum) : null,
                letzteWartung: f.letzteWartung ? new Date(f.letzteWartung) : null
            })));
            return true;
        } catch (err) {
            console.error('saveFilters Fehler:', err);
            return false;
        }
    },

    getFilters: async (stationId) => {
        try {
            const filters = await db.filters.where('stationId').equals(stationId).toArray();
            return JSON.stringify(filters);
        } catch (err) {
            console.error('getFilters Fehler:', err);
            return '[]';
        }
    },

    getAllFilters: async () => {
        try {
            const filters = await db.filters.toArray();
            return JSON.stringify(filters);
        } catch (err) {
            console.error('getAllFilters Fehler:', err);
            return '[]';
        }
    },

    enqueue: async (action, entityId, payload) => {
        try {
            const payloadJson = typeof payload === 'string' ? payload : JSON.stringify(payload);
            await db.outbox.add({
                action,
                entityId: entityId || 0,
                payload: payloadJson,
                timestamp: Date.now()
            });
            console.log(`Outbox: ${action} für ID ${entityId || 'neu'}`);
            return true;
        } catch (err) {
            console.error('enqueue Fehler:', err);
            return false;
        }
    },

    syncOutbox: async () => {
        if (!navigator.onLine) return false;

        try {
            const pending = await db.outbox.orderBy('timestamp').toArray();
            if (pending.length === 0) return true;

            console.log(`Sync: ${pending.length} Änderungen`);
            const baseUrl = 'https://filtercair-server-gwctc2gbf5f4axgj.westeurope-01.azurewebsites.net/api/Filter';

            for (const item of pending) {
                let success = false;

                try {
                    if (item.action === 'add') {
                        const res = await fetch(baseUrl, {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: item.payload
                        });
                        success = res.ok;
                        if (success) {
                            const newFilter = await res.json();
                            await db.filters.put(newFilter);
                            if (item.entityId === 0) {
                                await db.outbox.delete(item.id);
                            }
                        }
                    } else if (item.action === 'update') {
                        const payload = JSON.parse(item.payload);
                        const id = payload.id || item.entityId;
                        if (!id) {
                            console.error('Update ohne ID!', item);
                            await db.outbox.delete(item.id);
                            continue;
                        }

                        const res = await fetch(`${baseUrl}/${id}`, {
                            method: 'PUT',
                            headers: {
                                'Content-Type': 'application/json',
                                'Accept': 'application/json'
                            },
                            body: item.payload
                        });

                        if (!res.ok) {
                            console.error(`PUT ${id} fehlgeschlagen: ${res.status} ${res.statusText}`);
                            continue; // Nicht löschen – später erneut
                        }

                        success = true;
                        await db.filters.put(payload);
                        await db.outbox.delete(item.id);
                        console.log(`Update erfolgreich: ID ${id}`);
                    }
                } catch (err) {
                    console.error(`Sync Fehler bei ${item.action}:`, err);
                }

                if (success) {
                    // Nur bei Erfolg löschen – bereits oben
                }
            }

            // KEIN refreshAllFilters! API hat kein GET /api/Filter
            console.log('Sync abgeschlossen – keine globale Aktualisierung');
            return true;

        } catch (err) {
            console.error('syncOutbox Fehler:', err);
            return false;
        }
    },

    getPendingCount: async () => {
        return await db.outbox.count();
    }
};

// SIGNAL: filterDb ist vollständig geladen und bereit
window.filterDbReady = true;
console.log('filterDb bereit!');

// Online-Status für C# (falls benötigt)
window.navigator = window.navigator || {};
window.navigator.onLine = () => navigator.onLine;