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

namespace timetracker.Client.Services;

public class ClientTimetrackerService : ITimetrackerService
{
    private readonly HttpClient _http;
    private AppSettings? _cachedSettings;

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

    public async Task<List<WorkDay>> GetWeekAsync(int userId, DateOnly monday)
    {
        return await _http.GetFromJsonAsync<List<WorkDay>>($"api/tracker/week?monday={monday:yyyy-MM-dd}") ?? [];
    }

    public async Task UpsertWorkDayAsync(WorkDay workDay)
    {
        await _http.PostAsJsonAsync("api/tracker/workday", workDay);
    }

    public async Task<AppSettings> GetSettingsAsync(int userId)
    {
        if (_cachedSettings != null && _cachedSettings.UserId == userId)
        {
            return _cachedSettings;
        }
        var settings = await _http.GetFromJsonAsync<AppSettings>("api/tracker/settings");
        _cachedSettings = settings ?? new AppSettings { UserId = userId };
        return _cachedSettings;
    }

    public async Task SaveSettingsAsync(AppSettings settings)
    {
        await _http.PostAsJsonAsync("api/tracker/settings", settings);
        _cachedSettings = settings;
    }

    public async Task<List<VacationDay>> GetVacationDaysAsync(int userId, int year)
    {
        return await _http.GetFromJsonAsync<List<VacationDay>>($"api/tracker/vacation/{year}") ?? [];
    }

    public async Task AddVacationDayAsync(VacationDay vacationDay)
    {
        await _http.PostAsJsonAsync("api/tracker/vacation", vacationDay);
    }

    public async Task RemoveVacationDayAsync(int userId, int id)
    {
        await _http.DeleteAsync($"api/tracker/vacation/{id}");
    }

    public async Task<TimeSpan> GetTotalOvertimeAsync(int userId, AppSettings settings)
    {
        var response = await _http.PostAsJsonAsync("api/tracker/overtime", settings);
        if (response.IsSuccessStatusCode)
        {
            var hours = await response.Content.ReadFromJsonAsync<double>();
            return TimeSpan.FromHours(hours);
        }
        return TimeSpan.Zero;
    }

    public async Task<List<WorkDay>> GetMonthAsync(int userId, int year, int month)
    {
        return await _http.GetFromJsonAsync<List<WorkDay>>($"api/tracker/month?year={year}&month={month}") ?? [];
    }
}
