using AdsManagerService.API.Application.Queries;
using MediatR;
using Microsoft.AspNetCore.Mvc;

namespace AdsManagerService.API.Controllers;

/// <summary>
/// EN: API Controller for managing audiences.
/// VI: API Controller quản lý đối tượng mục tiêu.
/// </summary>
[ApiController]
[Route("api/v1/ads-manager/audiences")]
[Produces("application/json")]
public class AudiencesController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<AudiencesController> _logger;

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

    /// <summary>
    /// EN: List audiences for advertiser.
    /// VI: Liệt kê audiences cho nhà quảng cáo.
    /// </summary>
    [HttpGet]
    [ProducesResponseType(typeof(List<AudienceDto>), StatusCodes.Status200OK)]
    public async Task<ActionResult<List<AudienceDto>>> ListAudiences([FromQuery] Guid advertiserId)
    {
        _logger.LogInformation("Listing audiences for advertiser {AdvertiserId}", advertiserId);

        var audiences = await _mediator.Send(new ListAudiencesQuery { AdvertiserId = advertiserId });

        return Ok(audiences);
    }

    /// <summary>
    /// EN: Get audience by ID.
    /// VI: Lấy audience theo ID.
    /// </summary>
    [HttpGet("{id}")]
    [ProducesResponseType(typeof(AudienceDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<ActionResult<AudienceDto>> GetAudienceById(Guid id)
    {
        var audience = await _mediator.Send(new GetAudienceByIdQuery { AudienceId = id });

        if (audience == null)
            return NotFound();

        return Ok(audience);
    }
}

/// <summary>
/// EN: Audience DTO for API responses.
/// VI: Audience DTO cho API responses.
/// </summary>
public record AudienceDto
{
    public Guid Id { get; init; }
    public string Name { get; init; } = null!;
    public string Type { get; init; } = null!;
    public int Size { get; init; }
    public DateTime CreatedAt { get; init; }
}

/// <summary>
/// EN: Query to list audiences.
/// VI: Query liệt kê audiences.
/// </summary>
public record ListAudiencesQuery : IRequest<List<AudienceDto>>
{
    public Guid AdvertiserId { get; init; }
}

/// <summary>
/// EN: Query to get audience by ID.
/// VI: Query lấy audience theo ID.
/// </summary>
public record GetAudienceByIdQuery : IRequest<AudienceDto?>
{
    public Guid AudienceId { get; init; }
}
