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 VeapiPoolCore
    {
        private static readonly object _lockObj = new();
        private static IEnumerable<VeapiPoolDTO> _cached;
        public static VeapiPoolDTO? GetOne()
        {
            var list = List();
            if (!list.Any()) return null;
            return list.OrderBy(l => Guid.NewGuid()).FirstOrDefault();
        }
        public static VeapiPoolDTO? Get(int id)
        {
            var list = List();
            if (!list.Any()) return null;
            return list.Where(o => o.id == id).FirstOrDefault();
        }
        public static IEnumerable<VeapiPoolDTO> List(bool force = false)
        {
            if (!force && _cached != null) return _cached;

            string cache_key = $"cache:veapi_pool";
            var list = RedisHelper.Get<IEnumerable<VeapiPoolDTO>>(cache_key);
            if (force || list == null)
            {
                lock (_lockObj)
                {
                    list = new DBContext.Table("veapi_pool")
                        .Where("status=@status", new { status = 1 })
                        .Select<VeapiPoolDTO>();
                    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:veapi_pool:{name}:disabled";
            long count = RedisHelper.IncrBy(cache_key);
            if (count > 0) return;

            RedisHelper.Expire(cache_key, 10);

            new DBContext.Table("veapi_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.AnPushNotify("掉线", $"【veapi:{name}】cookie 掉线");
        }

    }

}
