using FluentValidation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Meezi.API.Models.Printing;
using Meezi.API.Services;
using Meezi.Core.Interfaces;
using Meezi.Shared;

namespace Meezi.API.Controllers;

[Route("api/cafes/{cafeId}/branches/{branchId}/pos-device")]
[Authorize(Roles = "Cashier,Manager,Owner")]
public class PosDeviceController : CafeApiControllerBase
{
    private readonly IPosDeviceService _posDevice;
    private readonly IValidator<PosPaymentRequest> _validator;

    public PosDeviceController(IPosDeviceService posDevice, IValidator<PosPaymentRequest> validator)
    {
        _posDevice = posDevice;
        _validator = validator;
    }

    [HttpPost("payment-request")]
    public async Task<IActionResult> RequestPayment(
        string cafeId,
        string branchId,
        [FromBody] PosPaymentRequest request,
        ITenantContext tenant,
        CancellationToken ct)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;

        var validation = await _validator.ValidateAsync(request, ct);
        if (!validation.IsValid) return BadRequest(ValidationError(validation));

        var result = await _posDevice.SendPaymentRequestAsync(cafeId, branchId, request, ct);

        if (!result.Success)
        {
            return BadRequest(new ApiResponse<object>(
                false,
                null,
                new ApiError(
                    result.ErrorCode ?? "POS_DEVICE_FAILED",
                    result.Detail ?? "Could not send amount to POS device.")));
        }

        return Ok(new ApiResponse<PosPaymentResultDto>(
            true,
            new PosPaymentResultDto(!result.Skipped, result.Skipped, null)));
    }
}
