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;
using Dataoke;
using System.Xml.Linq;
using System.Data;
using YunhuiKit;


namespace molilian.core
{
    public partial class ApiAccountCore
    {
        private static readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
        private static IEnumerable<ApiAccountDTO> _cached;
        public static async Task<ApiAccountDTO> GetOneAsync(string api_key)
        {
            var list = await ListAsync();
            if (!list.Any()) return null;
            return list.Where(e => e.api_key == api_key).FirstOrDefault();
        }


        //public static async Task<IEnumerable<ApiAccountDTO>> ListAsync(bool force = false)
        //{
        //    if (!force && _cached != null) return _cached;

        //    string cache_key = $"cache:api_key";
        //    var list = await RedisHelper.GetAsync<IEnumerable<ApiAccountDTO>>(cache_key);
        //    if (force || list == null)
        //    {
        //        lock (_lockObj)
        //        {
        //            list = new DBContext.Table("api_account").Select<ApiAccountDTO>();
        //            if (list == null) return default;
        //            _ = RedisHelper.SetAsync(cache_key, list, 30 * 86400);
        //        }
        //    }
        //    _cached = list;
        //    return list;
        //}

        public static async Task<IEnumerable<ApiAccountDTO>> ListAsync(bool force = false)
        {
            if (!force && _cached != null) return _cached;

            try
            {
                await _semaphore.WaitAsync();

                string cache_key = $"cache:api_key";
                var list = await RedisHelper.GetAsync<IEnumerable<ApiAccountDTO>>(cache_key);

                if (force || list == null)
                {
                    list = new DBContext.Table("api_account").Select<ApiAccountDTO>();
                    if (list == null) return default;

                    // 等待 Redis 写入完成
                    await RedisHelper.SetAsync(cache_key, list, 30 * 86400);
                }

                _cached = list;
                return list;
            }
            catch (Exception)
            {
                // 发生异常时返回上一次的缓存，如果没有则返回默认值
                return _cached ?? default;
            }
            finally
            {
                _semaphore.Release();
            }
        }

        public static void Refresh()
        {
            _ = ListAsync(true);
        }

        public static void Disabled(string name)
        {
            string cache_key = $"cache:api_key:{name}:disabled";
            long count = RedisHelper.IncrBy(cache_key);
            RedisHelper.Expire(cache_key, 10);
            if (count > 1) return;

            new DBContext.Table("api_account")
                .Add("status", 0)
                .Where("name=@name", new { name })
                .Update();
            _ = ListAsync(true);
            EndPointCore.NotifyReload();
        }


        public static int Update(ApiAccountDTO data, IDbConnection conn)
        {
            var result = (int)conn.Update<ApiAccountDTO>(data, new { data.id });
            _ = ListAsync(true);
#if DEBUG
#else
            EndPointCore.NotifyReload();
#endif
            return result;
        }

        public static int Create(ApiAccountDTO data, IDbConnection conn)
        {
            var result = (int)conn.Insert(data);
            _ = ListAsync(true);
#if DEBUG
#else
            EndPointCore.NotifyReload();
#endif
            return result;
        }


    }


}
