using Marco.Pms.Model.Dtos.PaymentGetway;
using Marco.Pms.Model.Utilities;
using Marco.Pms.Services.Service.ServiceInterfaces;
using MarcoBMS.Services.Helpers;
using MarcoBMS.Services.Service;
using Microsoft.AspNetCore.Mvc;

namespace Marco.Pms.Services.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class PaymentController : ControllerBase
    {
        private readonly UserHelper _userHelper;
        private readonly ILoggingService _logger;
        private readonly IRazorpayService _razorpayService;
        private readonly ITenantService _tenantService;
        private readonly Guid tenantId;
        private readonly Guid organizaionId;
        public PaymentController(UserHelper userHelper, ILoggingService logger, IRazorpayService razorpayService, ITenantService tenantService)
        {
            _userHelper = userHelper;
            _logger = logger;
            _razorpayService = razorpayService;
            tenantId = userHelper.GetTenantId();
            organizaionId = userHelper.GetCurrentOrganizationId();
            _tenantService = tenantService;
        }

        [HttpPost("create-order")]
        public async Task<IActionResult> CreateOrder([FromBody] CreateOrderDto model)
        {
            var loggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
            try
            {
                var response = _razorpayService.CreateOrder(model.Amount, loggedInEmployee, tenantId);
                return Ok(ApiResponse<object>.SuccessResponse(response, "Payment created successfully", 200));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<object>.ErrorResponse("Error occured While creating the payment", new
                {
                    Message = ex.Message,
                    StackTrace = ex.StackTrace,
                    Source = ex.Source,
                    InnerException = new
                    {
                        Message = ex.InnerException?.Message,
                        StackTrace = ex.InnerException?.StackTrace,
                        Source = ex.InnerException?.Source,
                    }
                }, 500));
            }
        }

        [HttpPost("verify-payment")]
        public async Task<IActionResult> VerifyPayment([FromBody] PaymentVerificationRequest request)
        {
            try
            {
                _logger.LogInfo("Payment verification started for OrderId: {OrderId}, PaymentId: {PaymentId}",
                    request.OrderId ?? "", request.PaymentId ?? "");

                // Validate request
                if (string.IsNullOrEmpty(request.OrderId) || string.IsNullOrEmpty(request.PaymentId) || string.IsNullOrEmpty(request.Signature))
                {
                    _logger.LogWarning("Payment verification failed - Missing required parameters");
                    return BadRequest(ApiResponse<object>.ErrorResponse("Missing required parameters", 400));
                }

                // Verify signature
                string payload = request.OrderId + "|" + request.PaymentId;
                string actualSignature = request.Signature;
                string expectedSignature = _razorpayService.GetExpectedSignature(payload);

                if (actualSignature == expectedSignature)
                {
                    _logger.LogInfo("Payment signature verified successfully for OrderId: {OrderId}", request.OrderId);

                    // Fetch complete payment details from Razorpay including card details
                    var response = await _razorpayService.GetPaymentDetails(request.PaymentId);

                    _logger.LogInfo("Invoice generated and saved for OrderId: {OrderId}", request.OrderId);

                    return Ok(ApiResponse<object>.SuccessResponse(response, "Payment verified successfully", 200));
                }
                else
                {
                    _logger.LogWarning("Payment signature verification failed for OrderId: {OrderId}", request.OrderId);
                    return BadRequest(ApiResponse<object>.ErrorResponse("Invalid signature - Payment verification failed", 400));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error during payment verification for OrderId: {OrderId}", request.OrderId ?? "");
                return StatusCode(500, ApiResponse<object>.ErrorResponse("An error occurred during payment verification", 500));
            }
        }

        [HttpGet("get/payment-details/{id}")]
        public async Task<IActionResult> GetPaymentDetails(Guid id)
        {
            var paymentsDetails = await _razorpayService.GetPaymentDetailsFromDataBase(id);
            return Ok(ApiResponse<object>.SuccessResponse(paymentsDetails, "Payment fetched Successfully", 200));
        }

    }

}

