using Microsoft.AspNetCore.Mvc;
using HoneyBox.Infrastructure.Cache;
using HoneyBox.Model.Base;
using HoneyBox.Model.Data;

namespace HoneyBox.Api.Controllers;

/// <summary>
/// 健康检查控制器 - 提供系统健康状态检查
/// </summary>
/// <remarks>
/// 检查数据库连接、Redis连接等系统组件的健康状态
/// </remarks>
[ApiController]
[Route("api/[controller]")]
public class HealthController : ControllerBase
{
    private readonly HoneyBoxDbContext _dbContext;
    private readonly ICacheService _cacheService;
    private readonly ILogger<HealthController> _logger;

    public HealthController(
        HoneyBoxDbContext dbContext,
        ICacheService cacheService,
        ILogger<HealthController> logger)
    {
        _dbContext = dbContext;
        _cacheService = cacheService;
        _logger = logger;
    }

    /// <summary>
    /// 获取服务健康状态
    /// </summary>
    /// <returns>健康检查结果</returns>
    [HttpGet]
    public async Task<ApiResponse<HealthCheckData>> GetHealth()
    {
        var healthData = new HealthCheckData
        {
            Timestamp = DateTime.Now
        };

        // 检查数据库连接状态
        try
        {
            var canConnect = await _dbContext.Database.CanConnectAsync();
            healthData.Database = canConnect ? "Connected" : "Disconnected";
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "数据库连接检查失败");
            healthData.Database = "Disconnected";
        }

        // 检查 Redis 连接状态
        try
        {
            var isRedisConnected = await _cacheService.IsConnectedAsync();
            healthData.Redis = isRedisConnected ? "Connected" : "Disconnected";
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Redis 连接检查失败");
            healthData.Redis = "Disconnected";
        }

        // 确定整体状态
        healthData.Status = (healthData.Database == "Connected" && healthData.Redis == "Connected")
            ? "Healthy"
            : "Unhealthy";

        return ApiResponse<HealthCheckData>.Success(healthData);
    }
}

/// <summary>
/// 健康检查响应数据
/// </summary>
public class HealthCheckData
{
    /// <summary>
    /// 整体状态
    /// </summary>
    public string Status { get; set; } = string.Empty;

    /// <summary>
    /// 数据库连接状态
    /// </summary>
    public string Database { get; set; } = string.Empty;

    /// <summary>
    /// Redis 连接状态
    /// </summary>
    public string Redis { get; set; } = string.Empty;

    /// <summary>
    /// 检查时间戳
    /// </summary>
    public DateTime Timestamp { get; set; }
}
