// EN: Controller for session management.
// VI: Controller quản lý phiên.

using Asp.Versioning;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using FnbEngine.API.Application.Commands;
using FnbEngine.API.Application.Queries;

namespace FnbEngine.API.Controllers;

/// <summary>
/// EN: Controller for session management.
/// VI: Controller quản lý phiên.
/// </summary>
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/sessions")]
public class SessionsController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<SessionsController> _logger;

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

    /// <summary>
    /// EN: Open a new session.
    /// VI: Mở phiên mới.
    /// </summary>
    [HttpPost]
    [ProducesResponseType(typeof(ApiResponse<OpenSessionResult>), 201)]
    [ProducesResponseType(400)]
    public async Task<ActionResult<ApiResponse<OpenSessionResult>>> OpenSession(
        [FromBody] OpenSessionRequest request,
        CancellationToken ct = default)
    {
        var command = new OpenSessionCommand(request.TableId, request.ShopId, request.GuestCount);
        var result = await _mediator.Send(command, ct);
        
        return CreatedAtAction(nameof(GetSession), new { id = result.SessionId },
            new ApiResponse<OpenSessionResult> { Success = true, Data = result });
    }

    /// <summary>
    /// EN: Get session details.
    /// VI: Lấy thông tin phiên.
    /// </summary>
    [HttpGet("{id}")]
    [ProducesResponseType(typeof(ApiResponse<SessionDto>), 200)]
    [ProducesResponseType(404)]
    public async Task<ActionResult<ApiResponse<SessionDto>>> GetSession(
        Guid id,
        CancellationToken ct = default)
    {
        var result = await _mediator.Send(new GetSessionQuery(id), ct);
        
        if (result == null)
            return NotFound(new ApiResponse<SessionDto> { Success = false, Error = "Session not found" });

        return Ok(new ApiResponse<SessionDto> { Success = true, Data = result });
    }

    /// <summary>
    /// EN: Close a session.
    /// VI: Đóng phiên.
    /// </summary>
    [HttpPost("{id}/close")]
    [ProducesResponseType(typeof(ApiResponse<bool>), 200)]
    [ProducesResponseType(404)]
    public async Task<ActionResult<ApiResponse<bool>>> CloseSession(
        Guid id,
        CancellationToken ct = default)
    {
        var result = await _mediator.Send(new CloseSessionCommand(id), ct);
        return Ok(new ApiResponse<bool> { Success = true, Data = result });
    }
}

/// <summary>
/// EN: Request to open a session.
/// VI: Request mở phiên.
/// </summary>
public record OpenSessionRequest(
    Guid TableId,
    Guid ShopId,
    int GuestCount = 1);
