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

namespace CMSMicroservice.Application.CommissionCQ.Commands.ApproveWithdrawal;

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

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

    public async Task<Unit> Handle(ApproveWithdrawalCommand 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 Withdrawn (approved)
        payout.Status = CommissionPayoutStatus.Withdrawn;
        payout.WithdrawnAt = DateTime.Now;
        payout.ProcessedBy = _currentUser.GetPerformedBy();
        payout.ProcessedAt = DateTime.Now;
        payout.LastModified = DateTime.Now;

        // TODO: Add PayoutHistory record
        // 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.Approved,
        //     Action = (int)CommissionPayoutAction.Approved,
        //     PerformedBy = "Admin", // TODO: Get from authenticated user
        //     Reason = request.Notes,
        //     Created = DateTime.Now
        // };
        // _context.CommissionPayoutHistories.Add(history);

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