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


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

        public StationService(HttpClient http, IConfiguration config, StationLocalService 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<StationModel>> GetStationsByCustomerAsync(int customerId)
        {
            bool isOnline = await IsOnlineAsync();

            if (!isOnline)
            {
                Console.WriteLine($"Offline → Stationen für Kunde {customerId} aus IndexedDB");
                return await _local.GetStationsAsync(customerId);
            }

            try
            {
                var stations = await _http.GetFromJsonAsync<List<StationModel>>($"{BaseUrl}/byCustomer/{customerId}");
                if (stations != null && stations.Count > 0)
                {
                    await _local.SaveStationsAsync(customerId, stations);
                }
                return stations ?? new();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"API-Fehler → Fallback auf IndexedDB: {ex.Message}");
                return await _local.GetStationsAsync(customerId);
            }
        }
    }
}