using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using dodohold.core;


namespace molilian.core
{
    public partial class OtherApiPoolCore
    {
        private static readonly object _lockObj = new();
        private static IEnumerable<OtherApiPoolDTO> _cached;
        public static OtherApiPoolDTO? GetOne()
        {
            var list = List();
            if (!list.Any()) return null;
            return list.OrderBy(l => Guid.NewGuid()).FirstOrDefault();
        }
        public static OtherApiPoolDTO? Get(int id)
        {
            var list = List();
            if (!list.Any()) return null;
            return list.Where(o => o.id == id).FirstOrDefault();
        }
        public static IEnumerable<OtherApiPoolDTO> List(bool force = false)
        {
            if (!force && _cached != null) return _cached;

            string cache_key = $"cache:other_api_pool";
            var list = RedisHelper.Get<IEnumerable<OtherApiPoolDTO>>(cache_key);
            if (force || list == null)
            {
                lock (_lockObj)
                {
                    list = new DBContext.Table("other_api_pool")
                        .Where("status=@status", new { status = 1 })
                        .Select<OtherApiPoolDTO>();
                    if (list == null) return default;
                    RedisHelper.Set(cache_key, list, 30 * 86400);
                }
            }
            _cached = list;
            return list;
        }
        public static void Refresh()
        {
            _ = List(true);
        }

        public static void Disabled(string name)
        {
            string cache_key = $"cache:other_api_pool:{name}:disabled";
            long count = RedisHelper.IncrBy(cache_key);
            if (count > 0) return;

            RedisHelper.Expire(cache_key, 10);

            new DBContext.Table("other_api_pool")
                .Add("status", 0)
                .Where("name=@name", new { name })
                .Update();
            _ = List(true);

            NotifyCore.Notify(new NifyMessage
            {
                message = $"【veapi:{name}】cookie 掉线",
                priority = NifyMessagePriority.high,
                tags = ["red_circle"]
            });
            NotifyCore.QYWeixinPushNotifyAsync("掉线", $"【第三方接口:{name}】cookie 掉线");
        }

    }

}
