using System.Collections.Generic;
using System.Threading.Tasks;
using MDL.Models;
using DAL.Interfaces;
using DB.Database;
using SqlSugar;

namespace DAL.Repositories
{
    /// <summary>
    /// 客户API信息的数据访问实现类
    /// </summary>
    public class CustomerApiRepository : ICustomerApiRepository
    {
        private readonly ISqlSugarProvider _provider;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="provider">SqlSugar数据库提供程序</param>
        public CustomerApiRepository(ISqlSugarProvider provider)
        {
            _provider = provider;
        }

        /// <summary>
        /// 创建客户API记录
        /// </summary>
        /// <param name="entity">客户API实体</param>
        /// <returns>创建的记录ID</returns>
        public async Task<int> CreateAsync(CustomerApiEntity entity)
        {
            var db = _provider.GetClient();

            // 确保表存在
            if (!db.DbMaintenance.IsAnyTable("customer_apis"))
            {
                db.CodeFirst.InitTables(typeof(CustomerApiEntity));
            }

            // 设置时间戳
            entity.CreatedAt = DateTime.UtcNow;
            entity.UpdatedAt = DateTime.UtcNow;

            // 插入数据并返回自增ID
            return await db.Insertable(entity).ExecuteReturnIdentityAsync();
        }

        /// <summary>
        /// 根据ID获取客户API记录
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <returns>客户API实体</returns>
        public async Task<CustomerApiEntity?> GetByIdAsync(int id)
        {
            var db = _provider.GetClient();
            return await db.Queryable<CustomerApiEntity>()
                .Where(x => x.Id == id)
                .FirstAsync();
        }

        /// <summary>
        /// 根据客户ID获取客户API记录
        /// </summary>
        /// <param name="customerId">客户ID</param>
        /// <returns>客户API实体列表</returns>
        public async Task<List<CustomerApiEntity>> GetByCustomerIdAsync(int customerId)
        {
            var db = _provider.GetClient();
            return await db.Queryable<CustomerApiEntity>()
                .Where(x => x.CustomerId == customerId)
                .ToListAsync();
        }

        /// <summary>
        /// 根据客户代码获取客户API记录
        /// </summary>
        /// <param name="customerCode">客户代码</param>
        /// <returns>客户API实体列表</returns>
        public async Task<List<CustomerApiEntity>> GetByCustomerCodeAsync(string customerCode)
        {
            var db = _provider.GetClient();
            return await db.Queryable<CustomerApiEntity>()
                .Where(x => x.CustomerCode == customerCode)
                .ToListAsync();
        }

        /// <summary>
        /// 根据API密钥获取客户API记录
        /// </summary>
        /// <param name="apiKey">API密钥</param>
        /// <returns>客户API实体</returns>
        public async Task<CustomerApiEntity?> GetByApiKeyAsync(string apiKey)
        {
            var db = _provider.GetClient();
            return await db.Queryable<CustomerApiEntity>()
                .Where(x => x.ApiKey == apiKey)
                .FirstAsync();
        }

        /// <summary>
        /// 验证客户API凭证并返回客户API信息
        /// </summary>
        /// <param name="customerCode">客户代码</param>
        /// <param name="apiKey">API密钥</param>
        /// <returns>客户API实体，如果验证失败则返回null</returns>
        public async Task<CustomerApiEntity?> ValidateAndGetApiCredentialsAsync(string customerCode, string apiKey)
        {
            var db = _provider.GetClient();
            
            // 查询有效（启用且未过期）的API密钥
            var now = DateTime.UtcNow;
            
            return await db.Queryable<CustomerApiEntity>()
                .Where(x => x.CustomerCode == customerCode && x.ApiKey == apiKey)
                .Where(x => x.Status == "Y")
                .Where(x => x.ExpireDate == null || x.ExpireDate > now)
                .FirstAsync();
        }
        
        /// <summary>
        /// 验证客户API凭证
        /// </summary>
        /// <param name="customerCode">客户代码</param>
        /// <param name="apiKey">API密钥</param>
        /// <returns>是否验证通过</returns>
        public async Task<bool> ValidateApiCredentialsAsync(string customerCode, string apiKey)
        {
            var result = await ValidateAndGetApiCredentialsAsync(customerCode, apiKey);
            return result != null;
        }

        /// <summary>
        /// 更新客户API记录
        /// </summary>
        /// <param name="entity">客户API实体</param>
        /// <returns>更新是否成功</returns>
        public async Task<bool> UpdateAsync(CustomerApiEntity entity)
        {
            var db = _provider.GetClient();

            // 更新时间戳
            entity.UpdatedAt = DateTime.UtcNow;

            // 更新数据并返回影响行数
            var rows = await db.Updateable(entity).ExecuteCommandAsync();
            return rows > 0;
        }

        /// <summary>
        /// 删除客户API记录
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <returns>删除是否成功</returns>
        public async Task<bool> DeleteAsync(int id)
        {
            var db = _provider.GetClient();
            var rows = await db.Deleteable<CustomerApiEntity>()
                .Where(x => x.Id == id)
                .ExecuteCommandAsync();
            return rows > 0;
        }

        /// <summary>
        /// 获取所有客户API记录
        /// </summary>
        /// <returns>客户API实体列表</returns>
        public async Task<List<CustomerApiEntity>> GetAllAsync()
        {
            var db = _provider.GetClient();
            return await db.Queryable<CustomerApiEntity>()
                .OrderByDescending(x => x.CreatedAt)
                .ToListAsync();
        }
    }
}