using System.Security.Authentication;
using FitConnect.Models;
using FitConnect.Services;
using FluentAssertions;
using NUnit.Framework;

namespace IntegrationTests;

public class OAuthServiceTest {
    private string _clientId = null!;
    private string _clientSecret = null!;
    private OAuthService _oAuthService = null!;

    [OneTimeSetUp]
    public void OneTimeSetup() {
        (_clientId, _clientSecret) = HelperMethods.GetSecrets();
    }


    [SetUp]
    public void SetUp() {
        var endpoints = FitConnectEnvironment.Testing;
        _oAuthService = new OAuthService(endpoints.TokenUrl, "v1", _clientId, _clientSecret, null);
    }

    [Test]
    public void GetAccessToken_ExpiresInShouldBe1800_WithoutScope() {
        _oAuthService.AuthenticateAsync().Wait();
        var token = _oAuthService.Token;
        token.Should().NotBeNull();
        token!.ExpiresIn.Should().Be(1800);
        token.Scope.Should().Be("send:region:DE");
    }

    [Test]
    public void GetAccessToken_WrongCredentials_ThrowInvalidCredentialException() {
        var exception = Assert.ThrowsAsync<InvalidCredentialException>(() =>
            new OAuthService(FitConnectEnvironment.Testing.TokenUrl, "v1", "wrong", "wrong",
                    null)
                .AuthenticateAsync()
        );
        exception!.Message.Replace(" ", "").Should().Contain("\"error\":\"invalid_client\"");
    }

    [Test]
    public void GetAccessToken_ScopeShouldMatch_WithScope() {
        _oAuthService.AuthenticateAsync("send:region:DE01010").Wait();
        var token = _oAuthService.Token;
        token.Should().NotBeNull();
        token!.ExpiresIn.Should().Be(1800);
        token.Scope.Should().Be("send:region:DE01010");
    }
}