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

namespace AdsTrackingService.API.Controllers;

/// <summary>
/// EN: Controller for tracking pixel management.
/// VI: Controller quản lý tracking pixel.
/// </summary>
[ApiController]
[Authorize]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/ads-tracking/pixels")]
public class PixelsController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<PixelsController> _logger;

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

    /// <summary>
    /// EN: Get pixel code for an advertiser.
    /// VI: Lấy pixel code cho advertiser.
    /// </summary>
    [HttpGet("{advertiserId:guid}")]
    [ProducesResponseType(typeof(PixelCodeDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<ActionResult<PixelCodeDto>> GetPixelCode(
        Guid advertiserId,
        CancellationToken ct)
    {
        var result = await _mediator.Send(new GetPixelCodeQuery(advertiserId), ct);
        
        if (result == null)
        {
            return NotFound(new { success = false, error = new { code = "NOT_FOUND", message = "Pixel not found for this advertiser" } });
        }

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

    /// <summary>
    /// EN: Create a new tracking pixel for an advertiser.
    /// VI: Tạo tracking pixel mới cho advertiser.
    /// </summary>
    [HttpPost]
    [ProducesResponseType(typeof(TrackingPixelResult), StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<ActionResult<TrackingPixelResult>> CreatePixel(
        [FromBody] CreatePixelRequest request,
        CancellationToken ct)
    {
        var command = new CreateTrackingPixelCommand(request.AdvertiserId);
        var result = await _mediator.Send(command, ct);

        _logger.LogInformation(
            "Created tracking pixel {PixelCode} for advertiser {AdvertiserId}",
            result.PixelCode, request.AdvertiserId);

        return CreatedAtAction(
            nameof(GetPixelCode),
            new { advertiserId = request.AdvertiserId },
            new { success = true, data = result });
    }
}

/// <summary>
/// EN: Request to create a tracking pixel.
/// VI: Request tạo tracking pixel.
/// </summary>
public record CreatePixelRequest(Guid AdvertiserId);
