using FilterCair.Client.Services.Local;
using FilterCair.Shared.Models;
using Microsoft.JSInterop;
using System.Net.Http.Json;

namespace FilterCair.Client.Services.API
{
    public class FilterService
    {
        private readonly HttpClient _http;
        private readonly IConfiguration _config;
        private readonly FilterLocalService _local;
        private readonly IJSRuntime _js;
        private string BaseUrl => _config["Api:BaseUrl"] + "/api/Filter";

        public FilterService(HttpClient http, IConfiguration config, FilterLocalService local, IJSRuntime js)
        {
            _http = http; _config = config; _local = local; _js = js;
        }

        private async Task<bool> IsOnlineAsync()
        {
            try { return await _js.InvokeAsync<bool>("navigator.onLine"); }
            catch { return true; }
        }

        public async Task<List<FilterModel>> GetFiltersByStationAsync(int stationId)
        {
            bool isOnline = await IsOnlineAsync();

            if (!isOnline)
            {
                Console.WriteLine($"Offline → Filter für Station {stationId} aus IndexedDB");
                return await _local.GetFiltersAsync(stationId);
            }

            try
            {
                var filters = await _http.GetFromJsonAsync<List<FilterModel>>($"{BaseUrl}/byStation/{stationId}");
                if (filters != null) await _local.SaveFiltersAsync(stationId, filters);
                return filters ?? new();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"API-Fehler → Fallback: {ex.Message}");
                return await _local.GetFiltersAsync(stationId);
            }
        }

        public async Task<bool> SaveFilterAsync(FilterModel filter)
        {
            bool isOnline = await IsOnlineAsync();

            if (isOnline)
            {
                try
                {
                    var response = filter.Id > 0
                        ? await _http.PutAsJsonAsync($"{BaseUrl}/{filter.Id}", filter)
                        : await _http.PostAsJsonAsync(BaseUrl, filter);

                    if (response.IsSuccessStatusCode)
                    {
                        var result = filter.Id > 0 ? filter : await response.Content.ReadFromJsonAsync<FilterModel>();
                        if (result != null) await _local.SaveFiltersAsync(filter.StationId, new[] { result }.ToList());
                        return true;
                    }
                }
                catch { }
            }



            // Offline: lokal + Outbox
            await _local.SaveFiltersAsync(filter.StationId, new[] { filter }.ToList());
            await _local.EnqueueAsync(filter.Id > 0 ? "update" : "add", filter.Id, filter);
            return true;
        }

        public async Task<FilterModel?> GetFilterByIdAsync(int id)
        {
            bool isOnline = await IsOnlineAsync();

            if (!isOnline)
            {
                // Offline: aus IndexedDB laden
                var allFilters = await _local.GetFiltersAsync(0); // 0 = alle Stationen ignorieren
                return allFilters.FirstOrDefault(f => f.Id == id);
            }

            try
            {
                var filter = await _http.GetFromJsonAsync<FilterModel>($"{BaseUrl}/{id}");
                if (filter != null)
                {
                    await _local.SaveFiltersAsync(filter.StationId, new[] { filter }.ToList());
                }
                return filter;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"API-Fehler bei GetFilterByIdAsync: {ex.Message}");
                // Fallback auf IndexedDB
                var localFilters = await _local.GetFiltersAsync(0);
                return localFilters.FirstOrDefault(f => f.Id == id);
            }
        }
    }




}
