using Asp.Versioning;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using AdsAnalyticsService.API.Application.Queries;

namespace AdsAnalyticsService.API.Controllers;

/// <summary>
/// EN: API Controller for ads analytics metrics.
/// VI: API Controller cho metrics phân tích quảng cáo.
/// </summary>
[ApiController]
[Authorize]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/ads-analytics")]
[Produces("application/json")]
public class MetricsController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<MetricsController> _logger;

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

    /// <summary>
    /// EN: Get campaign metrics for a date range.
    /// VI: Lấy metrics chiến dịch cho khoảng thời gian.
    /// </summary>
    /// <param name="id">Campaign ID</param>
    /// <param name="startDate">Start date (YYYY-MM-DD)</param>
    /// <param name="endDate">End date (YYYY-MM-DD)</param>
    /// <returns>Campaign metrics</returns>
    [HttpGet("campaigns/{id}/metrics")]
    [ProducesResponseType(typeof(CampaignMetricsDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<ActionResult<CampaignMetricsDto>> GetCampaignMetrics(
        Guid id,
        [FromQuery] DateTime? startDate = null,
        [FromQuery] DateTime? endDate = null)
    {
        // EN: Default to last 30 days if not specified
        // VI: Mặc định 30 ngày gần nhất nếu không chỉ định
        var start = startDate ?? DateTime.UtcNow.AddDays(-30).Date;
        var end = endDate ?? DateTime.UtcNow.Date;

        var query = new GetCampaignMetricsQuery
        {
            CampaignId = id,
            StartDate = start,
            EndDate = end
        };

        var metrics = await _mediator.Send(query);

        if (metrics == null)
            return NotFound(new { success = false, error = new { code = "NOT_FOUND", message = $"No metrics found for campaign {id}" } });

        return Ok(new { success = true, data = metrics });
    }

    /// <summary>
    /// EN: Get ad set metrics (placeholder for future implementation).
    /// VI: Lấy metrics ad set (placeholder cho triển khai sau).
    /// </summary>
    [HttpGet("adsets/{id}/metrics")]
    [ProducesResponseType(StatusCodes.Status501NotImplemented)]
    public IActionResult GetAdSetMetrics(Guid id)
    {
        _logger.LogWarning("AdSet metrics not yet implemented");
        return StatusCode(StatusCodes.Status501NotImplemented,
            new { success = false, error = new { code = "NOT_IMPLEMENTED", message = "AdSet metrics endpoint not yet implemented" } });
    }

    /// <summary>
    /// EN: Get ad metrics (placeholder for future implementation).
    /// VI: Lấy metrics ad (placeholder cho triển khai sau).
    /// </summary>
    [HttpGet("ads/{id}/metrics")]
    [ProducesResponseType(StatusCodes.Status501NotImplemented)]
    public IActionResult GetAdMetrics(Guid id)
    {
        _logger.LogWarning("Ad metrics not yet implemented");
        return StatusCode(StatusCodes.Status501NotImplemented,
            new { success = false, error = new { code = "NOT_IMPLEMENTED", message = "Ad metrics endpoint not yet implemented" } });
    }
}
