using System.Net.Http.Json;
using VideoStudy.Shared.Services;

namespace VideoStudy.Desktop.Services;

public class LicenseManager
{
    private readonly HttpClient _httpClient;
    private readonly IHardwareIdService _hardwareIdService;
    private string? _localToken;

    public LicenseManager(HttpClient httpClient, IHardwareIdService hardwareIdService)
    {
        _httpClient = httpClient;
        _hardwareIdService = hardwareIdService;
    }

    public bool IsActivated => !string.IsNullOrEmpty(_localToken);

    public async Task<string> ActivateAsync(string email)
    {
        var hwId = _hardwareIdService.GetHardwareId();
        var request = new { Email = email, HardwareId = hwId };

        var response = await _httpClient.PostAsJsonAsync("api/license/activate", request);
        
        if (response.IsSuccessStatusCode)
        {
            var result = await response.Content.ReadFromJsonAsync<LicenseResponse>();
            if (result != null && result.IsActive)
            {
                _localToken = result.Token;
                return "Success";
            }
            return result?.Message ?? "Unknown error";
        }
        
        return "Activation failed";
    }
}

public class LicenseResponse
{
    public bool IsActive { get; set; }
    public string Message { get; set; } = string.Empty;
    public string Token { get; set; } = string.Empty;
}
