namespace MiningService.API.ExternalServices;

/// <summary>
/// EN: Client interface for IAM Service communication.
/// VI: Interface client giao tiếp với IAM Service.
/// </summary>
public interface IIamServiceClient
{
    Task<UserInfo?> GetUserInfoAsync(Guid userId, CancellationToken cancellationToken = default);
    Task<bool> ValidateUserAsync(Guid userId, CancellationToken cancellationToken = default);
}

public record UserInfo(
    Guid UserId,
    string Email,
    string DisplayName,
    bool IsEmailVerified,
    bool IsKycVerified,
    DateTime CreatedAt);

/// <summary>
/// EN: HTTP client implementation for IAM Service.
/// VI: Triển khai HTTP client cho IAM Service.
/// </summary>
public class IamServiceClient : IIamServiceClient
{
    private readonly HttpClient _httpClient;
    private readonly ILogger<IamServiceClient> _logger;

    public IamServiceClient(HttpClient httpClient, ILogger<IamServiceClient> logger)
    {
        _httpClient = httpClient;
        _logger = logger;
    }

    public async Task<UserInfo?> GetUserInfoAsync(Guid userId, CancellationToken cancellationToken = default)
    {
        try
        {
            var response = await _httpClient.GetAsync($"/api/v1/users/{userId}", cancellationToken);
            if (!response.IsSuccessStatusCode)
            {
                _logger.LogWarning("Failed to get user info for {UserId}: {StatusCode}", userId, response.StatusCode);
                return null;
            }
            return await response.Content.ReadFromJsonAsync<UserInfo>(cancellationToken);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error calling IAM Service for user {UserId}", userId);
            return null;
        }
    }

    public async Task<bool> ValidateUserAsync(Guid userId, CancellationToken cancellationToken = default)
    {
        var userInfo = await GetUserInfoAsync(userId, cancellationToken);
        return userInfo != null && userInfo.IsEmailVerified;
    }
}
