// EN: POS Controller for Point of Sale operations.
// VI: Controller POS cho các thao tác bán hàng.

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

namespace MerchantService.API.Controllers;

/// <summary>
/// EN: Controller for POS (Point of Sale) operations.
/// VI: Controller cho các thao tác POS (Point of Sale).
/// </summary>
[ApiController]
[Route("api/v1/pos")]
public class PosController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<PosController> _logger;

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

    /// <summary>
    /// EN: Authenticate staff using PIN for POS operations.
    /// VI: Xác thực nhân viên sử dụng PIN cho hoạt động POS.
    /// </summary>
    [HttpPost("auth/pin")]
    [AllowAnonymous]
    [ProducesResponseType(typeof(PinAuthResult), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status401Unauthorized)]
    public async Task<IActionResult> PinAuth([FromBody] PinAuthRequest request)
    {
        var command = new PinAuthCommand
        {
            StaffId = request.StaffId,
            PinCode = request.PinCode,
            DeviceId = request.DeviceId
        };

        var result = await _mediator.Send(command);

        if (!result.IsAuthenticated)
        {
            return Unauthorized(new { message = result.ErrorMessage });
        }

        return Ok(result);
    }

    /// <summary>
    /// EN: Register a device for POS/push notifications.
    /// VI: Đăng ký thiết bị cho POS/push notifications.
    /// </summary>
    [HttpPost("devices/register")]
    [Authorize]
    [ProducesResponseType(typeof(RegisterDeviceResult), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> RegisterDevice([FromBody] RegisterDeviceRequest request)
    {
        try
        {
            var command = new RegisterDeviceCommand
            {
                DeviceId = request.DeviceId,
                DeviceName = request.DeviceName,
                Platform = request.Platform,
                PushToken = request.PushToken
            };

            var result = await _mediator.Send(command);
            _logger.LogInformation("Device registered: {DeviceId}", request.DeviceId);
            return Ok(result);
        }
        catch (Domain.Exceptions.DomainException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    /// <summary>
    /// EN: Get current staff information for POS.
    /// VI: Lấy thông tin nhân viên hiện tại cho POS.
    /// </summary>
    [HttpGet("me")]
    [Authorize]
    [ProducesResponseType(typeof(PosStaffDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetMe()
    {
        var result = await _mediator.Send(new GetPosStaffQuery());
        if (result == null)
        {
            return NotFound(new { message = "Staff not found" });
        }
        return Ok(result);
    }
}

#region Request Models

public record PinAuthRequest
{
    public Guid StaffId { get; init; }
    public string PinCode { get; init; } = null!;
    public string? DeviceId { get; init; }
}

public record RegisterDeviceRequest
{
    public string DeviceId { get; init; } = null!;
    public string DeviceName { get; init; } = null!;
    public string Platform { get; init; } = null!;
    public string? PushToken { get; init; }
}

#endregion
