using Atomx.Common.Constant;
using Atomx.Common.Entities;

namespace Atomx.Data.CacheServices
{
    public partial interface ICacheService
    {
        /// <summary>
        /// 获取用户基本信息
        /// </summary>
        /// <param name="agencyId"></param>
        /// <param name="reload"></param>
        /// <returns></returns>
        Task<User?> GetUserBaseInfo(long id, bool? reload = null);

        /// <summary>
        /// 更新用户缓存
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        Task<User> UpdateUserBaseInfo(User user);


    }

    public partial class CacheService : ICacheService
    {
        public async Task<User?> GetUserBaseInfo(long id, bool? reload = null)
        {
            var cacheData = await GetCacheAsync<User>($"{CacheKeys.UserPrefix}{id}");

            if (cacheData == null || reload.HasValue)
            {
                var data = _dbContext.Users.Where(p => p.Id == id).SingleOrDefault();
                if (data != null)
                {
                    cacheData = data;
                    await SetCacheAsync($"{CacheKeys.UserPrefix}{id}", cacheData, 0.5);
                }
            }

            return cacheData;
        }


        public async Task<User> UpdateUserBaseInfo(User user)
        {
            var cacheData = await GetCacheAsync<User>($"{CacheKeys.UserPrefix}{user.Id}");
            cacheData = user;
            await SetCacheAsync($"{CacheKeys.UserPrefix}{user.Id}", cacheData, 0.5);
            return cacheData;
        }



    }
}
