using FilterCair.Shared.Models;
using Microsoft.JSInterop;
using System.Text.Json;

namespace FilterCair.Client.Services.Local
{
    public class CustomerLocalService
    {
        private readonly IJSRuntime _js;

        public CustomerLocalService(IJSRuntime js)
        {
            _js = js;
        }

        public async Task SaveAllAsync(List<CustomerModel> customers)
        {
            var json = JsonSerializer.Serialize(customers, JsonOptions);
            try
            {
                await _js.InvokeVoidAsync("filterDb.saveAll", json);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"filterDb.saveAll fehlgeschlagen: {ex.Message}");
            }
        }

        public async Task<List<CustomerModel>> GetAllAsync()
        {
            try
            {
                Console.WriteLine("Lese aus IndexedDB...");
                var json = await _js.InvokeAsync<string>("filterDb.getAll");
                Console.WriteLine($"JS liefert JSON: {json?.Substring(0, Math.Min(100, json.Length))}...");

                if (string.IsNullOrEmpty(json) || json == "[]")
                    return new();

                var result = JsonSerializer.Deserialize<List<CustomerModel>>(json, JsonOptions);
                Console.WriteLine($"Deserialisiert: {result?.Count ?? 0} Kunden");
                return result ?? new();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"IndexedDB Fehler: {ex.Message}");
                return new();
            }
        }

        public async Task AddOrUpdateAsync(CustomerModel customer)
        {
            var json = JsonSerializer.Serialize(customer, JsonOptions);
            await _js.InvokeVoidAsync("filterDb.put", json);
        }

        public async Task DeleteAsync(int id)
        {
            await _js.InvokeVoidAsync("filterDb.delete", id);
        }

        private static readonly JsonSerializerOptions JsonOptions = new()
        {
            PropertyNameCaseInsensitive = true, 
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase
        };
    }
}