using IdentityModel.Client;

namespace Ladaer.BackEnd.Infrastructures.Services
{
    public class AuthService
    {
        private readonly HttpClient _httpClient;
        public AuthService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        public async Task<TokenResponse> LoginAsync(string username, string password)
        {
            var disco = await _httpClient.GetDiscoveryDocumentAsync("https://id.ladaexpress.vn");
            if (disco.IsError)
            {
                throw new Exception(disco.Error);
            }

            var tokenResponse = await _httpClient.RequestPasswordTokenAsync(new PasswordTokenRequest
            {
                Address = disco.TokenEndpoint,
                ClientId = "AppClients",
                ClientSecret = "kNbPZcuUMc6nufZ2oIJN",
                Scope = "BackEnd",
                UserName = username,
                Password = password
            });

            if (tokenResponse.IsError)
            {
                throw new Exception(tokenResponse.Error);
            }

            return tokenResponse;
        }
    }
}
