using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using StorageService.API.Application.Queries.Admin;
using Swashbuckle.AspNetCore.Annotations;
using Asp.Versioning;

namespace StorageService.API.Controllers.Admin;

/// <summary>
/// EN: Admin controller for storage statistics.
/// VI: Controller admin cho thống kê storage.
/// </summary>
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/admin/statistics")]
[Authorize(Roles = "Admin,SuperAdmin")]
[SwaggerTag("Admin Statistics - Dashboard statistics for storage")]
public class AdminStatisticsController : ControllerBase
{
    private readonly IMediator _mediator;

    public AdminStatisticsController(IMediator mediator)
    {
        _mediator = mediator;
    }

    /// <summary>
    /// EN: Get storage statistics.
    /// VI: Lấy thống kê storage.
    /// </summary>
    [HttpGet]
    [SwaggerOperation(Summary = "Get statistics", Description = "Get aggregated storage statistics for dashboard")]
    [SwaggerResponse(200, "Statistics retrieved successfully")]
    [SwaggerResponse(403, "Forbidden - Admin role required")]
    public async Task<ActionResult<ApiResponse<StorageStatisticsDto>>> GetStatistics(
        CancellationToken cancellationToken = default)
    {
        var query = new GetStorageStatisticsQuery();
        var result = await _mediator.Send(query, cancellationToken);

        return Ok(new ApiResponse<StorageStatisticsDto> { Success = true, Data = result });
    }

    /// <summary>
    /// EN: Get users near storage limit.
    /// VI: Lấy users gần hết quota.
    /// </summary>
    [HttpGet("users-near-limit")]
    [SwaggerOperation(Summary = "Get users near limit", Description = "Get users with usage >= 80%")]
    [SwaggerResponse(200, "Users retrieved successfully")]
    public async Task<ActionResult<ApiResponse<AllUsersQuotaResult>>> GetUsersNearLimit(
        [FromQuery] int pageNumber = 1,
        [FromQuery] int pageSize = 20,
        CancellationToken cancellationToken = default)
    {
        var query = new GetAllUsersQuotaQuery(
            pageNumber, pageSize, 
            null, // quotaTier
            80,   // minUsagePercentage = 80%
            "usedStorageBytes", 
            true  // descending - highest usage first
        );
        var result = await _mediator.Send(query, cancellationToken);

        return Ok(new ApiResponse<AllUsersQuotaResult> { Success = true, Data = result });
    }
}
