using Asp.Versioning;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using FacebookService.API.Application.Queries;
using FacebookService.API.Application.Dtos;

namespace FacebookService.API.Controllers;

/// <summary>
/// EN: Controller for Conversation management.
/// VI: Controller quản lý Conversation.
/// </summary>
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/conversations")]
[Produces("application/json")]
public class ConversationsController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<ConversationsController> _logger;

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

    /// <summary>
    /// EN: Get a conversation by ID.
    /// VI: Lấy conversation theo ID.
    /// </summary>
    [HttpGet("{id:guid}")]
    [ProducesResponseType(typeof(ConversationDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetConversation(
        Guid id, 
        [FromQuery] bool includeMessages = true)
    {
        var conversation = await _mediator.Send(
            new GetConversationByIdQuery(id, includeMessages));

        if (conversation is null)
        {
            return NotFound(new
            {
                success = false,
                error = new { code = "CONVERSATION_NOT_FOUND", message = $"Conversation with ID {id} not found" }
            });
        }

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

    /// <summary>
    /// EN: Get conversations for a shop with pagination.
    /// VI: Lấy danh sách conversations của shop với phân trang.
    /// </summary>
    [HttpGet]
    [ProducesResponseType(typeof(GetConversationsQueryResult), StatusCodes.Status200OK)]
    public async Task<IActionResult> GetConversations(
        [FromQuery] Guid? shopId = null,
        [FromQuery] string? status = null,
        [FromQuery] int skip = 0,
        [FromQuery] int take = 20)
    {
        var result = await _mediator.Send(
            new GetConversationsQuery(shopId, status, skip, take));

        return Ok(new { success = true, data = result.Conversations, total = result.TotalCount });
    }
}
