using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Tiku.Api.Contracts;
using Tiku.Application.Security;
using Tiku.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;

namespace Tiku.Api.Controllers;

[ApiController]
[Tags("平台端-系统健康")]
[AllowAnonymous]
[Produces("application/json")]
[Route("api/health")]
public sealed class HealthController(
    TikuDbContext dbContext,
    IRedisSecurityStore redisSecurityStore) : ControllerBase
{
    [HttpGet]
    [EndpointSummary("健康检查")]
    [EndpointDescription("用于本地、CI 和部署环境 smoke test 的轻量健康检查。")]
    [ProducesResponseType<HealthResponseDto>(StatusCodes.Status200OK)]
    public ActionResult<HealthResponseDto> Get()
    {
        return Ok(new HealthResponseDto(
            "ok",
            "tiku-api",
            DateTimeOffset.UtcNow));
    }

    [HttpGet("ready")]
    [EndpointSummary("依赖就绪检查")]
    public async Task<ActionResult<object>> Ready(CancellationToken cancellationToken)
    {
        var database = await dbContext.Database.CanConnectAsync(cancellationToken);
        var redis = !redisSecurityStore.IsConfigured || await redisSecurityStore.PingAsync(cancellationToken);
        var ready = database && redis;
        var response = new
        {
            status = ready ? "ready" : "not_ready",
            database,
            redis = new { configured = redisSecurityStore.IsConfigured, ready = redis },
            checkedAt = DateTimeOffset.UtcNow
        };
        return ready ? Ok(response) : StatusCode(StatusCodes.Status503ServiceUnavailable, response);
    }
}
