using System.Data;

namespace OpenWarehouse.auth.api.Common.RegisterTokenManager;

public class RegisterTokenManager(
    UserManager<ApplicationUser> userManager,
    RoleManager<ApplicationRole> roleManager,
    ApplicationDbContext context
    ) : IRegisterTokenManager
{
    public async Task<RegisterToken> AddNewToken(string token, ApplicationUser creator, List<string> avaliableRole)
    {
        var listRole = new List<ApplicationRole>();
        foreach (var role in avaliableRole)
        {
            var roleObj = await roleManager.FindByNameAsync(role);

            if (roleObj != null) listRole.Add(roleObj);
        }
        
        return await AddNewTolken(token, creator, listRole);
    }

    public async Task<RegisterToken> AddNewTolken(string token, ApplicationUser creator, List<ApplicationRole> avaliableRole)
    {
        var tokenObj = new RegisterToken()
        {
            Creator = creator,
            AvaliableRole = avaliableRole,
            Token = token
        };
        context.RegisterTokens.Add(tokenObj);

        if (await context.SaveChangesAsync() > 0)
        {
            return tokenObj;
        }
        else
        {
            throw new DataException();
        }
    }

    public async Task<RegisterToken?> GetToken(string token)
    {
        return await context.RegisterTokens.FirstOrDefaultAsync(registerToken => registerToken.Token.Equals(token));
    }
}