using NSubstitute;
using TeleWave.Application.Auth;
using TeleWave.Application.Auth.Login;
using TeleWave.Application.Common.Interfaces;
using TeleWave.Application.Common.Models;
using Xunit;

namespace TeleWave.Application.Tests.Auth;

public class LoginCommandHandlerTests
{
    private readonly IIdentityService _identityService = Substitute.For<IIdentityService>();
    private readonly IJwtTokenService _jwtTokenService = Substitute.For<IJwtTokenService>();
    private readonly IRefreshTokenService _refreshTokenService =
        Substitute.For<IRefreshTokenService>();

    private LoginCommandHandler CreateHandler() =>
        new(_identityService, _jwtTokenService, _refreshTokenService);

    [Fact]
    public async Task Handle_WithValidCredentials_ReturnsAuthResult()
    {
        var userId = Guid.NewGuid();
        _identityService
            .ValidateCredentialsAsync("alice", "password123", Arg.Any<CancellationToken>())
            .Returns(Result.Success(new AuthenticatedUser(userId, "alice", "user")));
        _identityService
            .GetProfileAsync(userId, Arg.Any<CancellationToken>())
            .Returns(new CurrentUserProfile(userId, "alice", "user", IsBlocked: false));
        _jwtTokenService
            .GenerateAccessToken(Arg.Any<AuthenticatedUser>())
            .Returns(("access-token", DateTimeOffset.UtcNow.AddMinutes(15)));
        _refreshTokenService
            .IssueAsync(userId, Arg.Any<CancellationToken>())
            .Returns(new IssuedRefreshToken("refresh-token", DateTimeOffset.UtcNow.AddDays(30)));

        var result = await CreateHandler()
            .Handle(new LoginCommand("alice", "password123"), CancellationToken.None);

        Assert.True(result.IsSuccess);
        Assert.Equal("access-token", result.Value.AccessToken);
        Assert.Equal("refresh-token", result.Value.RefreshToken);
    }

    [Fact]
    public async Task Handle_WithInvalidCredentials_ReturnsFailure()
    {
        _identityService
            .ValidateCredentialsAsync("alice", "wrong", Arg.Any<CancellationToken>())
            .Returns(Result.Failure<AuthenticatedUser>(AuthErrors.InvalidCredentials));

        var result = await CreateHandler()
            .Handle(new LoginCommand("alice", "wrong"), CancellationToken.None);

        Assert.False(result.IsSuccess);
        Assert.Equal(AuthErrors.InvalidCredentials, result.Error);
    }

    [Fact]
    public async Task Handle_WhenUserIsBlocked_ReturnsBlockedFailure()
    {
        var userId = Guid.NewGuid();
        _identityService
            .ValidateCredentialsAsync("alice", "password123", Arg.Any<CancellationToken>())
            .Returns(Result.Success(new AuthenticatedUser(userId, "alice", "user")));
        _identityService
            .GetProfileAsync(userId, Arg.Any<CancellationToken>())
            .Returns(new CurrentUserProfile(userId, "alice", "user", IsBlocked: true));

        var result = await CreateHandler()
            .Handle(new LoginCommand("alice", "password123"), CancellationToken.None);

        Assert.False(result.IsSuccess);
        Assert.Equal(AuthErrors.Blocked, result.Error);
    }
}
