using System.Net.Http.Json;
using timetracker.Shared;

namespace timetracker.Client.Services;

public class ClientHolidayService : IHolidayService
{
    private readonly HttpClient _http;
    private readonly Dictionary<(int Year, string StateCode), List<PublicHoliday>> _holidayCache = new();

    public ClientHolidayService(HttpClient http)
    {
        _http = http;
    }

    public async Task<List<PublicHoliday>> GetHolidaysAsync(int year, string? stateCode = null)
    {
        var sc = stateCode ?? "";
        var key = (year, sc);
        if (_holidayCache.TryGetValue(key, out var cached))
        {
            return cached;
        }

        var url = $"api/holidays?year={year}";
        if (!string.IsNullOrEmpty(stateCode))
        {
            url += $"&stateCode={stateCode}";
        }
        var result = await _http.GetFromJsonAsync<List<PublicHoliday>>(url) ?? [];
        _holidayCache[key] = result;
        return result;
    }

    public async Task<(bool Success, string Message)> FetchAndStoreAsync(int year)
    {
        var response = await _http.PostAsync($"api/holidays/fetch/{year}", null);
        if (response.IsSuccessStatusCode)
        {
            var result = await response.Content.ReadFromJsonAsync<FetchResponse>();
            if (result != null)
            {
                // Invalidate the cache for this year
                var keysToRemove = _holidayCache.Keys.Where(k => k.Year == year).ToList();
                foreach (var k in keysToRemove)
                {
                    _holidayCache.Remove(k);
                }
                return (result.Success, result.Message);
            }
        }
        return (false, "Fehler beim Abrufen der Feiertage.");
    }

    public async Task DeleteAsync(int id)
    {
        await _http.DeleteAsync($"api/holidays/{id}");
        // Invalidate all caches since we deleted a holiday
        _holidayCache.Clear();
    }

    private class FetchResponse
    {
        public bool Success { get; set; }
        public string Message { get; set; } = "";
    }
}
