namespace Application.Domain;

public class AreaService : IAreaService, ITransient
{
    private readonly ISqlSugarClient _dbClient;
    private readonly IRedisCache _redisClient;

    public AreaService(ISqlSugarClient dbClient, IRedisCache redisClient)
    {
        _dbClient = dbClient;
        _redisClient = redisClient;
    }

    /// <summary>
    /// 获取所有区服
    /// </summary>
    /// <returns></returns>
    public async Task<List<game_area>> GetAreaData()
    {
        string key = string.Format(BaseCache.BaseCacheKey, "AreaData");
        if (await _redisClient.ExistsAsync(key))
        {
            return await _redisClient.GetAsync<List<game_area>>(key);
        }
        else
        {
            var db = _dbClient.AsTenant().GetConnectionWithAttr<game_area>();
            var data = await db.Queryable<game_area>().ToListAsync();
            await _redisClient.SetAsync(key, data);
            return data;
        }
    }

    public async Task<game_area> GetAreaInfo(int areaId)
    {
        string key = string.Format(BaseCache.BaseCacheKeys, "AreaData", areaId);
        if (await _redisClient.ExistsAsync(key))
        {
            return await _redisClient.GetAsync<game_area>(key);
        }
        else
        {
            var db = _dbClient.AsTenant().GetConnectionWithAttr<game_area>();
            var data = await db.Queryable<game_area>().Where(it => it.areaId == areaId).SingleAsync();
            await _redisClient.SetAsync(key, data);
            return data;
        }
    }

    private async Task ClearAreaCache(int areaId = 0)
    {
        string key = string.Format(BaseCache.BaseCacheKey, "AreaData");
        await _redisClient.DelAsync(key);
        if (areaId != 0)
        {
            key = string.Format(BaseCache.BaseCacheKeys, "AreaData", areaId);
            await _redisClient.DelAsync(key);
        }
    }
}