using Eshop.Application.Auth;
using Eshop.Infrastructure.Persistence;
using Microsoft.AspNetCore.Identity;

namespace Eshop.Infrastructure.Identity;

public class AspNetIdentityAuthenticationService(
    UserManager<UserEntity> users,
    SignInManager<UserEntity> signIn) : IAuthenticationService
{
    public async Task<SignInResultDto> SignInAsync(
        string emailOrUsername,
        string password,
        bool rememberMe,
        CancellationToken cancellationToken)
    {
        var user = emailOrUsername.Contains('@')
            ? await users.FindByEmailAsync(emailOrUsername)
            : await users.FindByNameAsync(emailOrUsername);

        if (user is null)
            return SignInResultDto.Failure;

        var result = await signIn.PasswordSignInAsync(user, password, rememberMe, lockoutOnFailure: false);
        return result.Succeeded ? SignInResultDto.Success : SignInResultDto.Failure;
    }

    public Task SignOutAsync(CancellationToken cancellationToken) =>
        signIn.SignOutAsync();
}
