using System.Net.Http;
using System.Net.Http.Json;
using FluentResults;
using NexusReader.Application.DTOs.User;
using NexusReader.Domain.Enums;
using NexusReader.Application.Abstractions.Services;

namespace NexusReader.Web.Client.Services;

public class CloudUserPreferenceStore : IUserPreferenceStore
{
    private readonly IHttpClientFactory _httpClientFactory;

    public CloudUserPreferenceStore(IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }

    private HttpClient CreateClient() => _httpClientFactory.CreateClient("NexusAPI");

    public async Task<Result> SaveThemePreferenceAsync(ThemeMode mode)
    {
        try
        {
            var client = CreateClient();
            var response = await client.PostAsJsonAsync("identity/theme", new UpdateThemeRequest(mode));
            if (response.IsSuccessStatusCode)
            {
                return Result.Ok();
            }
            
            var error = await response.Content.ReadAsStringAsync();
            return Result.Fail($"Failed to save cloud theme preference: {error}");
        }
        catch (Exception ex)
        {
            return Result.Fail(new Error("Network error saving theme preference to cloud.").CausedBy(ex));
        }
    }

    public async Task<Result<ThemeMode>> GetThemePreferenceAsync()
    {
        try
        {
            var client = CreateClient();
            var response = await client.GetAsync("identity/profile");
            if (response.IsSuccessStatusCode)
            {
                var profile = await response.Content.ReadFromJsonAsync<UserProfileDto>();
                return profile != null 
                    ? Result.Ok(profile.ThemePreference) 
                    : Result.Fail("Failed to deserialize profile response.");
            }
            return Result.Fail($"Failed to fetch theme preference from cloud: {response.ReasonPhrase}");
        }
        catch (Exception ex)
        {
            return Result.Fail(new Error("Network error retrieving theme preference from cloud.").CausedBy(ex));
        }
    }
}
