using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.DiscountShopCQ.Commands.CompleteOrderPayment;

public class CompleteOrderPaymentCommandHandler : IRequestHandler<CompleteOrderPaymentCommand, CompleteOrderPaymentResponseDto>
{
    private readonly IApplicationDbContext _context;

    public CompleteOrderPaymentCommandHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<CompleteOrderPaymentResponseDto> Handle(CompleteOrderPaymentCommand request, CancellationToken cancellationToken)
    {
        var order = await _context.DiscountOrders
            .Include(o => o.OrderDetails)
                .ThenInclude(od => od.Product)
            .FirstOrDefaultAsync(o => o.Id == request.OrderId, cancellationToken);

        if (order == null)
        {
            return new CompleteOrderPaymentResponseDto
            {
                Success = false,
                Message = "سفارش یافت نشد"
            };
        }

        var transaction = await _context.Transactions
            .FirstOrDefaultAsync(t => t.Id == request.TransactionId, cancellationToken);

        if (transaction == null)
        {
            return new CompleteOrderPaymentResponseDto
            {
                Success = false,
                Message = "تراکنش یافت نشد"
            };
        }

        if (request.PaymentSuccess)
        {
            // Update transaction
            transaction.PaymentStatus = PaymentStatus.Success;
            transaction.PaymentDate = DateTime.UtcNow;
            transaction.RefId = request.RefId;

            // Update order
            order.PaymentStatus = PaymentStatus.Success;
            order.PaymentDate = DateTime.UtcNow;
            order.DeliveryStatus = DeliveryStatus.InTransit;

            // Deduct discount balance from user wallet
            var userWallet = await _context.UserWallets
                .FirstOrDefaultAsync(w => w.UserId == order.UserId, cancellationToken);

            if (userWallet != null)
            {
                userWallet.DiscountBalance -= order.DiscountBalanceUsed;
            }

            // Update product stock and sale count
            foreach (var orderDetail in order.OrderDetails)
            {
                var product = orderDetail.Product;
                product.RemainingCount -= orderDetail.Count;
                product.SaleCount += orderDetail.Count;
            }

            await _context.SaveChangesAsync(cancellationToken);

            return new CompleteOrderPaymentResponseDto
            {
                Success = true,
                Message = "پرداخت با موفقیت انجام شد",
                OrderId = order.Id
            };
        }
        else
        {
            // Payment failed
            transaction.PaymentStatus = PaymentStatus.Reject;
            order.PaymentStatus = PaymentStatus.Reject;

            await _context.SaveChangesAsync(cancellationToken);

            return new CompleteOrderPaymentResponseDto
            {
                Success = false,
                Message = "پرداخت ناموفق بود",
                OrderId = order.Id
            };
        }
    }
}
