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

namespace FilterCair.Client.Services.Local
{
    // Services/Local/FilterLocalService.cs
    public class FilterLocalService
    {
        private readonly IJSRuntime _js;
        public FilterLocalService(IJSRuntime js) => _js = js;

        public async Task SaveFiltersAsync(int stationId, List<FilterModel> filters)
        {
            var json = JsonSerializer.Serialize(filters, JsonOptions);
            await _js.InvokeVoidAsync("filterDb.saveFilters", stationId, json);
        }

        public async Task<List<FilterModel>> GetFiltersAsync(int stationId)
        {
            try
            {
                if (stationId == 0)
                {
                    // Alle Filter laden
                    var json = await _js.InvokeAsync<string>("filterDb.getAllFilters");
                    return JsonSerializer.Deserialize<List<FilterModel>>(json, JsonOptions) ?? new();
                }
                else
                {
                    var json = await _js.InvokeAsync<string>("filterDb.getFilters", stationId);
                    return JsonSerializer.Deserialize<List<FilterModel>>(json, JsonOptions) ?? new();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"GetFiltersAsync Fehler: {ex.Message}");
                return new();
            }
        }

        public async Task EnqueueAsync(string action, int entityId, FilterModel payload)
        {
            var payloadJson = JsonSerializer.Serialize(payload, JsonOptions);
            await _js.InvokeVoidAsync("filterDb.enqueue", action, entityId, payloadJson);
        }

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