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

namespace ChatService.API.Controllers;

/// <summary>
/// EN: Controller for conversation management.
/// VI: Controller để quản lý cuộc hội thoại.
/// </summary>
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class ConversationsController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<ConversationsController> _logger;

    public ConversationsController(IMediator mediator, ILogger<ConversationsController> logger)
    {
        _mediator = mediator;
        _logger = logger;
    }

    /// <summary>
    /// EN: Create a new conversation.
    /// VI: Tạo cuộc hội thoại mới.
    /// </summary>
    [HttpPost]
    [ProducesResponseType(typeof(CreateConversationResult), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> CreateConversation([FromBody] CreateConversationRequest request)
    {
        var command = new CreateConversationCommand(
            request.CreatorId,
            request.ParticipantIds,
            request.Name,
            request.AvatarUrl,
            request.IsGroup);

        try
        {
            var result = await _mediator.Send(command);
            return Ok(result);
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(ex.Message);
        }
    }

    /// <summary>
    /// EN: Get user's conversations.
    /// VI: Lấy các cuộc hội thoại của user.
    /// </summary>
    [HttpGet]
    [ProducesResponseType(typeof(GetConversationsResult), StatusCodes.Status200OK)]
    public async Task<IActionResult> GetConversations(
        [FromQuery] Guid userId,
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 20)
    {
        var query = new GetConversationsQuery(userId, page, pageSize);
        var result = await _mediator.Send(query);
        return Ok(result);
    }

    /// <summary>
    /// EN: Get a specific conversation by ID.
    /// VI: Lấy cuộc hội thoại theo ID.
    /// </summary>
    [HttpGet("{conversationId:guid}")]
    [ProducesResponseType(typeof(ConversationDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetConversation(Guid conversationId, [FromQuery] Guid userId)
    {
        var query = new GetConversationsQuery(userId, 1, 1);
        var result = await _mediator.Send(query);
        
        var conversation = result.Conversations.FirstOrDefault(c => c.Id == conversationId);
        if (conversation == null)
        {
            return NotFound($"Conversation {conversationId} not found");
        }

        return Ok(conversation);
    }
}

#region Request DTOs

public record CreateConversationRequest(
    Guid CreatorId,
    List<Guid> ParticipantIds,
    string? Name = null,
    string? AvatarUrl = null,
    bool IsGroup = false
);

#endregion
