using ERPCore.Dtos.Auth;
using ERPCore.Infra.Auth.AuthHex;
using ERPCore.Services.Interfaces;
using ERPCore.System.Errors;

namespace ERPCore.Services.Auth;

/// <inheritdoc cref="IAuthAltService"/>
public sealed class AuthAltService : IAuthAltService
{
    private readonly IAuthHexClient _authHex;

    public AuthAltService(IAuthHexClient authHex) => _authHex = authHex;

    public Task<IsAvailableResponse> IsAvailableAsync(IsAvailableRequest request, CancellationToken ct = default)
        => _authHex.IsAvailableAsync(request, ct);

    public Task<SendOtpResponse> SendOtpAsync(SendOtpRequest request, CancellationToken ct = default)
        => _authHex.SendOtpAsync(request, ct);

    public async Task<OtpAuthSessionResult> VerifyOtpAsync(VerifyAltOtpRequest request, CancellationToken ct = default)
    {
        var result = await _authHex.VerifyAltOtpAsync(request, ct);
        if (result is null || string.IsNullOrEmpty(result.AccessToken) || string.IsNullOrEmpty(result.RefreshToken))
            throw new DomainException(ErrorCodes.AuthUpstreamError, "The authentication service did not return a session.", 502);

        return new OtpAuthSessionResult
        {
            AccessToken = result.AccessToken,
            RefreshToken = result.RefreshToken,
            Body = new OtpLoginVerifiedResponse
            {
                ReferenceNumber = result.ReferenceNumber,
                UserId = result.UserId,
                Verified = result.Verified ?? true,
                User = result.User,
                ExpiresIn = result.ExpiresIn
            }
        };
    }
}
