using CMSMicroservice.Domain.Enums;
using CMSMicroservice.Application.Common.Exceptions;

namespace CMSMicroservice.Application.CommissionCQ.Commands.RejectWithdrawal;

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

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

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

        if (payout == null)
        {
            throw new NotFoundException($"Payout با شناسه {request.PayoutId} یافت نشد");
        }

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

        // Update status to Cancelled (rejected)
        payout.Status = CommissionPayoutStatus.Cancelled;
        payout.ProcessedBy = _currentUser.GetPerformedBy();
        payout.ProcessedAt = DateTime.Now;
        payout.RejectionReason = request.Reason;
        payout.LastModified = DateTime.Now;

        // TODO: Add PayoutHistory record with rejection reason
        // var history = new CommissionPayoutHistory
        // {
        //     PayoutId = payout.Id,
        //     UserId = payout.UserId,
        //     WeekNumber = payout.WeekNumber,
        //     AmountBefore = payout.TotalAmount,
        //     AmountAfter = payout.TotalAmount,
        //     OldStatus = (int)CommissionPayoutStatus.Pending,
        //     NewStatus = (int)CommissionPayoutStatus.Rejected,
        //     Action = (int)CommissionPayoutAction.Rejected,
        //     PerformedBy = "Admin", // TODO: Get from authenticated user
        //     Reason = request.Reason,
        //     Created = DateTime.Now
        // };
        // _context.CommissionPayoutHistories.Add(history);

        await _context.SaveChangesAsync(cancellationToken);
        return Unit.Value;
    }
}
