using CMSMicroservice.Application.Common;

namespace CMSMicroservice.Application.CommissionCQ.Commands.RequestWithdrawal;

public class RequestWithdrawalCommandHandler : IRequestHandler<RequestWithdrawalCommand, Unit>
{
    private readonly IApplicationDbContext _context;
    private readonly ICurrentUserService _currentUser;

    public RequestWithdrawalCommandHandler(
        IApplicationDbContext context,
        ICurrentUserService currentUser)
    {
        _context = context;
        _currentUser = currentUser;
    }

    public async Task<Unit> Handle(RequestWithdrawalCommand request, CancellationToken cancellationToken)
    {
        var payout = await _context.UserCommissionPayouts
            .FirstOrDefaultAsync(x => x.Id == request.PayoutId, cancellationToken);

        if (payout == null)
        {
            throw new NotFoundException(nameof(UserCommissionPayout), request.PayoutId);
        }

        // بررسی وضعیت
        if (payout.Status != CommissionPayoutStatus.Paid)
        {
            throw new InvalidOperationException($"فقط پرداخت‌های با وضعیت Paid قابل برداشت هستند. وضعیت فعلی: {payout.Status}");
        }

        var oldStatus = payout.Status;

        // به‌روزرسانی وضعیت
        payout.Status = CommissionPayoutStatus.WithdrawRequested;
        payout.WithdrawalMethod = request.Method;

        if (request.Method == WithdrawalMethod.Cash)
        {
            var normalizedIban = IbanNormalizer.TryNormalize(request.IbanNumber);
            if (normalizedIban is null)
                throw new InvalidOperationException("فرمت شماره شبا معتبر نیست. باید IR و ۲۴ رقم باشد.");
            payout.IbanNumber = normalizedIban;
        }

        _context.UserCommissionPayouts.Update(payout);
        await _context.SaveChangesAsync(cancellationToken);

        // ثبت تاریخچه
        var history = new CommissionPayoutHistory
        {
            UserCommissionPayoutId = payout.Id,
            UserId = payout.UserId,
            WeekDefinitionId = payout.WeekDefinitionId,
            AmountBefore = payout.TotalAmount,
            AmountAfter = payout.TotalAmount,
            OldStatus = oldStatus,
            NewStatus = CommissionPayoutStatus.WithdrawRequested,
            Action = CommissionPayoutAction.WithdrawRequested,
            PerformedBy = "User", // TODO: باید از Current User گرفته شود
            Reason = $"درخواست برداشت به روش {request.Method}"
        };

        await _context.CommissionPayoutHistories.AddAsync(history, cancellationToken);
        await _context.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}
