using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TakeoutSaaS.Domain.Dictionary.Entities;
using TakeoutSaaS.Domain.Dictionary.Repositories;
using TakeoutSaaS.Infrastructure.Dictionary.Caching;
using TakeoutSaaS.Shared.Abstractions.Results;
using TakeoutSaaS.Shared.Web.Api;

namespace TakeoutSaaS.AdminApi.Controllers;

/// <summary>
/// 缓存监控指标接口。
/// </summary>
[ApiVersion("1.0")]
[Authorize(Roles = "PlatformAdmin")]
[Route("api/admin/v{version:apiVersion}/dictionary/metrics")]
public sealed class CacheMetricsController(
    CacheMetricsCollector metricsCollector,
    ICacheInvalidationLogRepository invalidationLogRepository)
    : BaseApiController
{
    /// <summary>
    /// 获取缓存统计信息。
    /// </summary>
    [HttpGet("cache-stats")]
    [ProducesResponseType(typeof(ApiResponse<CacheStatsSnapshot>), StatusCodes.Status200OK)]
    public ApiResponse<CacheStatsSnapshot> GetCacheStats([FromQuery] string? timeRange = "1h")
    {
        var window = timeRange?.ToLowerInvariant() switch
        {
            "24h" => TimeSpan.FromHours(24),
            "7d" => TimeSpan.FromDays(7),
            _ => TimeSpan.FromHours(1)
        };

        var snapshot = metricsCollector.GetSnapshot(window);
        return ApiResponse<CacheStatsSnapshot>.Ok(snapshot);
    }

    /// <summary>
    /// 获取缓存失效事件列表。
    /// </summary>
    [HttpGet("invalidation-events")]
    [ProducesResponseType(typeof(ApiResponse<PagedResult<CacheInvalidationLog>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<PagedResult<CacheInvalidationLog>>> GetInvalidationEvents(
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 20,
        [FromQuery] DateTime? startDate = null,
        [FromQuery] DateTime? endDate = null,
        CancellationToken cancellationToken = default)
    {
        var safePage = page <= 0 ? 1 : page;
        var safePageSize = pageSize <= 0 ? 20 : pageSize;

        var (items, total) = await invalidationLogRepository.GetPagedAsync(
            safePage,
            safePageSize,
            startDate,
            endDate,
            cancellationToken);

        var result = new PagedResult<CacheInvalidationLog>(items, safePage, safePageSize, total);
        return ApiResponse<PagedResult<CacheInvalidationLog>>.Ok(result);
    }
}
