using Hotline.Caching.Interfaces;
using Hotline.CallCenter.Tels;
using XF.Domain.Cache;
using XF.Domain.Dependency;
using XF.Domain.Exceptions;

namespace Hotline.Caching.Services;

public class TelCacheManager : ITelCacheManager, IScopeDependency
{
    private readonly ITypedCache<Tel> _cacheTel;
    private readonly ITypedCache<IReadOnlyList<Tel>> _cacheTelList;
    private readonly ITypedCache<TelGroup> _cacheTelGroup;
    private readonly ITelRepository _telRepository;
    private readonly ITelGroupRepository _telGroupRepository;

    public TelCacheManager(
        ITypedCache<Tel> cacheTel,
        ITypedCache<IReadOnlyList<Tel>> cacheTelList,
        ITypedCache<TelGroup> cacheTelGroup,
        ITelRepository telRepository,
        ITelGroupRepository telGroupRepository
        )
    {
        _cacheTel = cacheTel;
        _cacheTelList = cacheTelList;
        _cacheTelGroup = cacheTelGroup;
        _telRepository = telRepository;
        _telGroupRepository = telGroupRepository;
    }

    public Tel GetTel(string telNo)
    {
        var tel = _cacheTel.GetOrSet(telNo, k =>
        {
            var dbTel = _telRepository.GetExtAsync(d => d.No == telNo, d => d.Includes(x => x.Groups))
                .GetAwaiter().GetResult();
            if (dbTel == null)
                throw new UserFriendlyException("无效分机号");
            return dbTel;
        });
        return tel;
    }

    public TelGroup GetTelGroup(string groupNo)
    {
        var group = _cacheTelGroup.GetOrSet(groupNo, k =>
        {
            var telGroup = _telGroupRepository.GetExtAsync(d => d.No == groupNo, d => d.Includes(x => x.Tels))
                .GetAwaiter().GetResult();
            if (telGroup == null)
                throw new UserFriendlyException("无效分机组编号");
            return telGroup;
        });
        return group;
    }

    public IReadOnlyList<Tel> GetTels()
    {
        return _cacheTelList.GetOrSet("tellist", d => _telRepository.QueryAsync(x => !x.IsDeleted).GetAwaiter().GetResult()) ?? new List<Tel>();
    }
}