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

namespace MktZaloService.API.Controllers;

/// <summary>
/// EN: Controller for managing conversations.
/// VI: Controller để quản lý cuộc hội thoại.
/// </summary>
[ApiController]
[Route("api/v1/conversations")]
[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: Get conversation history with paginated messages.
    /// VI: Lấy lịch sử cuộc hội thoại với tin nhắn phân trang.
    /// </summary>
    [HttpGet("{id:guid}")]
    public async Task<ActionResult<ConversationHistoryDto>> GetConversation(
        Guid id,
        [FromQuery] int skip = 0,
        [FromQuery] int take = 50,
        CancellationToken ct = default)
    {
        var query = new GetConversationHistoryQuery(id, skip, take);
        var result = await _mediator.Send(query, ct);

        if (result == null)
        {
            return NotFound(new { error = "Conversation not found" });
        }

        return Ok(result);
    }

    /// <summary>
    /// EN: Send a message to a conversation.
    /// VI: Gửi tin nhắn đến cuộc hội thoại.
    /// </summary>
    [HttpPost("{id:guid}/messages")]
    public async Task<ActionResult<SendMessageResult>> SendMessage(
        Guid id,
        [FromBody] SendMessageRequest request,
        CancellationToken ct = default)
    {
        var command = new SendMessageCommand(id, request.Text, IsFromBot: false);
        var result = await _mediator.Send(command, ct);

        if (!result.Success)
        {
            return BadRequest(new { error = result.Error });
        }

        return Ok(result);
    }
}

/// <summary>
/// EN: Request to send a message.
/// VI: Request để gửi tin nhắn.
/// </summary>
public record SendMessageRequest(string Text);
