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

namespace AdsManagerService.API.Controllers;

/// <summary>
/// EN: API Controller for managing individual ads.
/// VI: API Controller quản lý quảng cáo.
/// </summary>
[ApiController]
[Authorize]
[Route("api/v1/ads-manager/ads")]
[Produces("application/json")]
public class AdsController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<AdsController> _logger;

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

    /// <summary>
    /// EN: Create a new ad.
    /// VI: Tạo quảng cáo mới.
    /// </summary>
    [HttpPost]
    [ProducesResponseType(StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<ActionResult<Guid>> CreateAd([FromBody] CreateAdCommand command)
    {
        _logger.LogInformation("Creating ad for ad set {AdSetId}", command.AdSetId);

        var adId = await _mediator.Send(command);

        return CreatedAtAction(nameof(GetAdById), new { id = adId }, new { success = true, data = adId });
    }

    /// <summary>
    /// EN: Get ad by ID.
    /// VI: Lấy quảng cáo theo ID.
    /// </summary>
    [HttpGet("{id}")]
    [ProducesResponseType(typeof(AdDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<ActionResult<AdDto>> GetAdById(Guid id)
    {
        var ad = await _mediator.Send(new GetAdByIdQuery { AdId = id });

        if (ad == null)
            return NotFound(new { success = false, error = new { code = "NOT_FOUND", message = "Ad not found" } });

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

    /// <summary>
    /// EN: Submit ad for review.
    /// VI: Gửi quảng cáo để duyệt.
    /// </summary>
    [HttpPost("{id}/submit")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> SubmitAdForReview(Guid id)
    {
        _logger.LogInformation("Submitting ad {AdId} for review", id);

        var result = await _mediator.Send(new SubmitAdForReviewCommand { AdId = id });

        if (!result)
            return NotFound(new { success = false, error = new { code = "NOT_FOUND", message = "Ad not found" } });

        return NoContent();
    }
}
