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

namespace AdsTrackingService.API.Controllers.Admin;

/// <summary>
/// EN: Admin controller for pixel management and statistics.
/// VI: Controller admin quản lý pixel và thống kê.
/// </summary>
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/admin/ads-tracking/pixels")]
public class AdminPixelsController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<AdminPixelsController> _logger;

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

    /// <summary>
    /// EN: Get all tracking pixels with pagination.
    /// VI: Lấy tất cả tracking pixels với phân trang.
    /// </summary>
    [HttpGet]
    [ProducesResponseType(typeof(List<PixelListDto>), StatusCodes.Status200OK)]
    public async Task<ActionResult<List<PixelListDto>>> GetPixels(
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 20,
        [FromQuery] bool? isActive = null,
        CancellationToken ct = default)
    {
        // EN: Mock implementation - would use a proper admin query
        // VI: Implementation giả - sẽ dùng admin query thực tế
        var pixels = new List<PixelListDto>
        {
            new(Guid.NewGuid(), Guid.NewGuid(), "ABC123DEF456", true, DateTime.UtcNow)
        };

        _logger.LogInformation("Admin: Listed {Count} pixels", pixels.Count);
        return Ok(pixels);
    }

    /// <summary>
    /// EN: Get pixel event history.
    /// VI: Lấy lịch sử events của pixel.
    /// </summary>
    [HttpGet("{pixelId:guid}/events")]
    [ProducesResponseType(typeof(List<PixelEventDto>), StatusCodes.Status200OK)]
    public async Task<ActionResult<List<PixelEventDto>>> GetPixelEvents(
        Guid pixelId,
        [FromQuery] DateTime? from = null,
        [FromQuery] DateTime? to = null,
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 50,
        CancellationToken ct = default)
    {
        var events = new List<PixelEventDto>();
        _logger.LogInformation("Admin: Listed events for pixel {PixelId}", pixelId);
        return Ok(events);
    }

    /// <summary>
    /// EN: Get pixel statistics.
    /// VI: Lấy thống kê pixel.
    /// </summary>
    [HttpGet("{pixelId:guid}/stats")]
    [ProducesResponseType(typeof(PixelStatsDto), StatusCodes.Status200OK)]
    public async Task<ActionResult<PixelStatsDto>> GetPixelStats(
        Guid pixelId,
        [FromQuery] DateTime? from = null,
        [FromQuery] DateTime? to = null,
        CancellationToken ct = default)
    {
        var stats = new PixelStatsDto(
            pixelId,
            TotalEvents: 1000,
            EventsByType: new Dictionary<string, int>
            {
                ["PageView"] = 500,
                ["Click"] = 300,
                ["Conversion"] = 200
            }
        );

        _logger.LogInformation("Admin: Retrieved stats for pixel {PixelId}", pixelId);
        return Ok(stats);
    }

    /// <summary>
    /// EN: Activate a tracking pixel.
    /// VI: Kích hoạt tracking pixel.
    /// </summary>
    [HttpPut("{pixelId:guid}/activate")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> ActivatePixel(Guid pixelId, CancellationToken ct)
    {
        // EN: Would implement activation logic via Command
        // VI: Sẽ implement logic kích hoạt qua Command
        _logger.LogInformation("Admin: Activated pixel {PixelId}", pixelId);
        return Ok(new { Message = "Pixel activated successfully" });
    }

    /// <summary>
    /// EN: Deactivate a tracking pixel.
    /// VI: Vô hiệu hóa tracking pixel.
    /// </summary>
    [HttpPut("{pixelId:guid}/deactivate")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> DeactivatePixel(Guid pixelId, CancellationToken ct)
    {
        // EN: Would implement deactivation logic via Command
        // VI: Sẽ implement logic vô hiệu hóa qua Command
        _logger.LogInformation("Admin: Deactivated pixel {PixelId}", pixelId);
        return Ok(new { Message = "Pixel deactivated successfully" });
    }
}

// DTOs for Admin Pixels
public record PixelListDto(Guid Id, Guid AdvertiserId, string PixelCode, bool IsActive, DateTime CreatedAt);
public record PixelEventDto(Guid Id, string EventType, DateTime Timestamp, Guid UserId);
public record PixelStatsDto(Guid PixelId, int TotalEvents, Dictionary<string, int> EventsByType);
