namespace MinicsConsole.Business;

public class UserOperator(OrmCollections ormCollections, ILog log)
{
    public Task<UserAuthority> TryLogin(string userName, string password)
    {
        if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
            return Task.FromResult(UserAuthority.Failed);

        AutoResetEvent autoResetEvent = new(false);
        UserAuthority userAuthority = UserAuthority.Failed;
        ormCollections.MainORM?.Query<UserInfo>("UserAuthority",
                info => string.Equals(info.UserName, userName) && string.Equals(info.Password, password),
                user =>
                {
                    if (user is null || user.Count == 0)
                    {
                        userAuthority = UserAuthority.Deinded;
                        autoResetEvent.Set();
                        return;
                    }
                    userAuthority = user.First().Authority;
                    autoResetEvent.Set();
                }
            ).Wait();

        if (!autoResetEvent.WaitOne(2000))
            return Task.FromResult(UserAuthority.Failed);

        log.Info($"Login - User: {userName} - UserAuthority: {userAuthority}");

        return Task.FromResult(userAuthority);
    }

    public void CreateBaseUsers()
    {
        ormCollections.MainORM?.CreateTable<UserInfo>("UserAuthority");

        UserInfo userInfo = new()
        {
            UserName = "Operator",
            Password = "Aa123456".ToBase64(),
            Authority = UserAuthority.Operator
        };
        ormCollections.MainORM?.Insert("UserAuthority", userInfo);


        userInfo = new()
        {
            UserName = "Engineer",
            Password = "Aa123456".ToBase64(),
            Authority = UserAuthority.Engineer
        };
        ormCollections.MainORM?.Insert("UserAuthority", userInfo);

        userInfo = new()
        {
            UserName = "Zixuan",
            Password = "WnR0MTk5MzA1Mjkh",
            Authority = UserAuthority.God
        };
        ormCollections.MainORM?.Insert("UserAuthority", userInfo);
    }
}
