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

namespace AdsTrackingService.API.Controllers;

/// <summary>
/// EN: Controller for conversion tracking and attribution.
/// VI: Controller theo dõi conversion và attribution.
/// </summary>
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/ads-tracking/conversions")]
public class ConversionsController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<ConversionsController> _logger;

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

    /// <summary>
    /// EN: Get conversions with optional filtering.
    /// VI: Lấy danh sách conversions với bộ lọc tùy chọn.
    /// </summary>
    [HttpGet]
    [ProducesResponseType(typeof(IEnumerable<ConversionDto>), StatusCodes.Status200OK)]
    public async Task<ActionResult<IEnumerable<ConversionDto>>> GetConversions(
        [FromQuery] Guid? campaignId = null,
        [FromQuery] Guid? userId = null,
        [FromQuery] DateTime? from = null,
        [FromQuery] DateTime? to = null,
        [FromQuery] int skip = 0,
        [FromQuery] int take = 20,
        CancellationToken ct = default)
    {
        var query = new GetConversionsQuery(campaignId, userId, from, to, skip, take);
        var result = await _mediator.Send(query, ct);

        return Ok(result);
    }

    /// <summary>
    /// EN: Get attribution details for a specific conversion.
    /// VI: Lấy chi tiết attribution cho conversion cụ thể.
    /// </summary>
    [HttpGet("{id:guid}/attribution")]
    [ProducesResponseType(typeof(AttributionDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<ActionResult<AttributionDto>> GetAttributionDetails(
        Guid id,
        CancellationToken ct)
    {
        var query = new GetAttributionDetailsQuery(id);
        var result = await _mediator.Send(query, ct);

        if (result == null)
        {
            return NotFound(new { Message = "Attribution not found for this conversion" });
        }

        return Ok(result);
    }
}
