using ManagementPage.Database;
using ManagementPage.Models;
using MongoDB.Bson;
using MongoDB.Driver;

namespace ManagementPage.Auth
{
    public class AccountBinder
    {
        private readonly MongoDbClient _dbClient;
        public AccountBinder(MongoDbClient dbClient)
        {
            _dbClient = dbClient;
        }

        public async Task<UserData> GetLocalAccount(string OpenID)
        {
            // lookup ID

            var filter = new BsonDocument("OpenId", OpenID );
            var userData = await _dbClient.AccountsCollection.Find(filter).SingleOrDefaultAsync();
            if(userData == null)
            {
                userData = await BindNewAccount(OpenID);
            }

            return userData;
        }
        private async Task<UserData> BindNewAccount(string OpenID)
        {
            var user = new UserData(OpenID, ObjectId.GenerateNewId(), new List<ObjectId>());
            await _dbClient.AccountsCollection.InsertOneAsync(user);
            return user;
        }
    }
}
