using MediatR;
using Microsoft.AspNetCore.Mvc;

namespace AdsManagerService.API.Controllers;

/// <summary>
/// EN: Admin API Controller for reports and analytics.
/// VI: API Controller Admin cho báo cáo và phân tích.
/// </summary>
[ApiController]
[Route("api/v1/admin/ads-manager/reports")]
[Produces("application/json")]
public class AdminReportsController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<AdminReportsController> _logger;

    public AdminReportsController(IMediator mediator, ILogger<AdminReportsController> logger)
    {
        _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    /// <summary>
    /// EN: Get top advertisers by spend.
    /// VI: Lấy top advertisers theo chi tiêu.
    /// </summary>
    [HttpGet("top-advertisers")]
    [ProducesResponseType(typeof(List<TopAdvertiserDto>), StatusCodes.Status200OK)]
    public async Task<ActionResult<List<TopAdvertiserDto>>> GetTopAdvertisers([FromQuery] int limit = 10)
    {
        var advertisers = await _mediator.Send(new GetTopAdvertisersQuery { Limit = limit });
        return Ok(advertisers);
    }

    /// <summary>
    /// EN: Get revenue analytics.
    /// VI: Lấy phân tích doanh thu.
    /// </summary>
    [HttpGet("revenue")]
    [ProducesResponseType(typeof(RevenueAnalyticsDto), StatusCodes.Status200OK)]
    public async Task<ActionResult<RevenueAnalyticsDto>> GetRevenueAnalytics(
        [FromQuery] DateTime? startDate,
        [FromQuery] DateTime? endDate)
    {
        var analytics = await _mediator.Send(new GetRevenueAnalyticsQuery
        {
            StartDate = startDate,
            EndDate = endDate
        });

        return Ok(analytics);
    }
}

/// <summary>
/// EN: Top advertiser DTO.
/// VI: DTO top advertiser.
/// </summary>
public record TopAdvertiserDto
{
    public Guid AdvertiserId { get; init; }
    public int TotalCampaigns { get; init; }
    public decimal TotalSpend { get; init; }
    public int ActiveCampaigns { get; init; }
}

/// <summary>
/// EN: Revenue analytics DTO.
/// VI: DTO phân tích doanh thu.
/// </summary>
public record RevenueAnalyticsDto
{
    public decimal TotalRevenue { get; init; }
    public decimal AverageRevenuePerCampaign { get; init; }
    public int TotalCampaigns { get; init; }
    public Dictionary<string, decimal> RevenueByObjective { get; init; } = new();
}

/// <summary>
/// EN: Query to get top advertisers.
/// VI: Query lấy top advertisers.
/// </summary>
public record GetTopAdvertisersQuery : IRequest<List<TopAdvertiserDto>>
{
    public int Limit { get; init; } = 10;
}

/// <summary>
/// EN: Query to get revenue analytics.
/// VI: Query lấy phân tích doanh thu.
/// </summary>
public record GetRevenueAnalyticsQuery : IRequest<RevenueAnalyticsDto>
{
    public DateTime? StartDate { get; init; }
    public DateTime? EndDate { get; init; }
}
