using System.Text.Json;
using HoneyBox.Admin.Business.Attributes;
using HoneyBox.Admin.Business.Models;
using HoneyBox.Admin.Business.Models.Config;
using HoneyBox.Admin.Business.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;

namespace HoneyBox.Admin.Business.Controllers;

/// <summary>
/// 系统配置管理控制器
/// </summary>
[Route("api/admin/business/config")]
public class ConfigController : BusinessControllerBase
{
    private readonly IAdminConfigService _configService;

    public ConfigController(IAdminConfigService configService)
    {
        _configService = configService;
    }

    /// <summary>
    /// 获取配置
    /// </summary>
    /// <param name="key">配置键</param>
    /// <returns>配置数据</returns>
    [HttpGet("{key}")]
    [BusinessPermission("config:view")]
    public async Task<IActionResult> GetConfig(string key)
    {
        // 验证配置键是否有效
        if (!ConfigKeys.IsValidKey(key))
        {
            return ValidationError($"不支持的配置键: {key}");
        }

        var configValue = await _configService.GetConfigRawAsync(key);
        if (string.IsNullOrEmpty(configValue))
        {
            return Ok(new ConfigResponse
            {
                Key = key,
                Value = null
            });
        }

        try
        {
            // 尝试解析为JSON对象
            var jsonValue = JsonSerializer.Deserialize<object>(configValue);
            return Ok(new ConfigResponse
            {
                Key = key,
                Value = jsonValue
            });
        }
        catch
        {
            // 如果解析失败，返回原始字符串
            return Ok(new ConfigResponse
            {
                Key = key,
                Value = configValue
            });
        }
    }


    /// <summary>
    /// 更新配置
    /// </summary>
    /// <param name="key">配置键</param>
    /// <param name="request">配置更新请求</param>
    /// <returns>更新结果</returns>
    [HttpPut("{key}")]
    [BusinessPermission("config:edit")]
    public async Task<IActionResult> UpdateConfig(string key, [FromBody] ConfigUpdateRequest request)
    {
        // 验证配置键是否有效
        if (!ConfigKeys.IsValidKey(key))
        {
            return ValidationError($"不支持的配置键: {key}");
        }

        if (request.Value == null)
        {
            return ValidationError("配置值不能为空");
        }

        try
        {
            // 将配置值序列化为JSON字符串
            var jsonValue = JsonSerializer.Serialize(request.Value);

            // 验证配置
            var validationError = await _configService.ValidateConfigAsync(key, jsonValue);
            if (!string.IsNullOrEmpty(validationError))
            {
                return ValidationError(validationError);
            }

            // 更新配置
            var result = await _configService.UpdateConfigRawAsync(key, jsonValue);
            if (result)
            {
                return Ok("配置更新成功");
            }
            else
            {
                return Error(BusinessErrorCodes.InternalError, "配置更新失败");
            }
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
        catch (Exception)
        {
            return Error(BusinessErrorCodes.InternalError, "配置更新失败");
        }
    }

    /// <summary>
    /// 清理配置缓存
    /// </summary>
    /// <param name="key">配置键</param>
    /// <returns>清理结果</returns>
    [HttpDelete("{key}/cache")]
    [BusinessPermission("config:edit")]
    public async Task<IActionResult> ClearConfigCache(string key)
    {
        // 验证配置键是否有效
        if (!ConfigKeys.IsValidKey(key))
        {
            return ValidationError($"不支持的配置键: {key}");
        }

        await _configService.ClearConfigCacheAsync(key);
        return Ok("缓存清理成功");
    }

    /// <summary>
    /// 获取所有支持的配置键
    /// </summary>
    /// <returns>配置键列表</returns>
    [HttpGet("keys")]
    public IActionResult GetConfigKeys()
    {
        return Ok(ConfigKeys.AllKeys);
    }

    /// <summary>
    /// 清除所有用户海报缓存
    /// </summary>
    /// <returns>清除结果</returns>
    [HttpDelete("poster-cache")]
    [BusinessPermission("config:edit")]
    public async Task<IActionResult> ClearAllPosterCache()
    {
        try
        {
            var count = await _configService.ClearAllPosterCacheAsync();
            return Ok(new { message = $"成功清除 {count} 条海报缓存", count });
        }
        catch (Exception)
        {
            return Error(BusinessErrorCodes.InternalError, "清除海报缓存失败");
        }
    }
}
