using Asp.Versioning;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using AdsTrackingService.API.Application.Commands;
using AdsTrackingService.Domain.AggregatesModel.TrackingPixelAggregate;

namespace AdsTrackingService.API.Controllers;

/// <summary>
/// EN: Controller for tracking pixel events.
/// VI: Controller theo dõi sự kiện pixel.
/// </summary>
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/ads-tracking/events")]
public class EventsController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<EventsController> _logger;

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

    /// <summary>
    /// EN: Track a pixel event (client-side tracking).
    /// VI: Theo dõi sự kiện pixel (tracking phía client).
    /// </summary>
    [HttpPost]
    [ProducesResponseType(StatusCodes.Status202Accepted)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> TrackPixelEvent(
        [FromBody] TrackPixelEventRequest request,
        CancellationToken ct)
    {
        var command = new TrackPixelEventCommand(
            request.PixelCode,
            request.AdId,
            request.UserId,
            request.EventType,
            Request.Headers.UserAgent.ToString(),
            HttpContext.Connection.RemoteIpAddress?.ToString()
        );

        var success = await _mediator.Send(command, ct);

        if (!success)
        {
            return BadRequest(new { Message = "Invalid pixel code or pixel is not active" });
        }

        return Accepted(new { Message = "Event tracked successfully" });
    }

    /// <summary>
    /// EN: Track a server-side event (no pixel required).
    /// VI: Theo dõi sự kiện server-side (không cần pixel).
    /// </summary>
    [HttpPost("server")]
    [ProducesResponseType(StatusCodes.Status202Accepted)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> TrackServerSideEvent(
        [FromBody] TrackServerSideEventRequest request,
        CancellationToken ct)
    {
        // EN: Server-side events bypass pixel validation
        // VI: Sự kiện server-side bỏ qua validation pixel
        var command = new TrackPixelEventCommand(
            string.Empty, // No pixel code for server-side
            request.AdId,
            request.UserId,
            request.EventType,
            null,
            null
        );

        await _mediator.Send(command, ct);

        _logger.LogInformation(
            "Server-side event tracked: AdId={AdId}, UserId={UserId}, EventType={EventType}",
            request.AdId, request.UserId, request.EventType);

        return Accepted(new { Message = "Server-side event tracked successfully" });
    }
}

/// <summary>
/// EN: Request to track a pixel event.
/// VI: Request theo dõi sự kiện pixel.
/// </summary>
public record TrackPixelEventRequest(
    string PixelCode,
    Guid AdId,
    Guid UserId,
    PixelEventType EventType
);

/// <summary>
/// EN: Request to track a server-side event.
/// VI: Request theo dõi sự kiện server-side.
/// </summary>
public record TrackServerSideEventRequest(
    Guid AdId,
    Guid UserId,
    PixelEventType EventType
);
