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;


namespace molilian.core
{
    public class ApiAccountDTO
    {
        public int id { get; set; }
        public string name { get; set; } = string.Empty;
        public string api_key { get; set; } = string.Empty;
        public string api_secret { get; set; } = string.Empty;
        public string description { get; set; } = string.Empty;
        public DateTime create_time { get; set; }
        public DateTime last_time { get; set; }
        public bool status { get; set; }
        public int interval { get; set; }
        public bool enable_report { get; set; } = false;
    }

    public partial class ApiAccountCore
    {
        private static readonly object _lockObj = new();
        private static IEnumerable<ApiAccountDTO> _cached;
        public static ApiAccountDTO? GetOne(string api_key)
        {
            var list = List();
            if (!list.Any()) return null;
            return list.Where(e => e.api_key == api_key).FirstOrDefault();
        }


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

            string cache_key = $"cache:api_key";
            var list = RedisHelper.Get<IEnumerable<ApiAccountDTO>>(cache_key);
            if (force || list == null)
            {
                lock (_lockObj)
                {
                    list = new DBContext.Table("api_account").Select<ApiAccountDTO>();
                    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: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();
            _ = List(true);
            EndPointCore.NotifyReload();
        }


    }


}
