namespace Netina.Core.EntityServices.MarketerHandlers;

public class CreateMarketerDiscountCommandHandler : IRequestHandler<CreateMarketerDiscountCommand, string>
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly IRepositoryWrapper _repositoryWrapper;
    private readonly ICurrentUserService _currentUserService;
    private readonly ISettingService _settingService;

    public CreateMarketerDiscountCommandHandler(UserManager<ApplicationUser> userManager,
        IRepositoryWrapper repositoryWrapper,
        ICurrentUserService currentUserService,
        ISettingService settingService)
    {
        _userManager = userManager;
        _repositoryWrapper = repositoryWrapper;
        _currentUserService = currentUserService;
        _settingService = settingService;
    }
    public async Task<string> Handle(CreateMarketerDiscountCommand request, CancellationToken cancellationToken)
    {
        var userId = request.MarketerUserId;
        if (userId == default)
        {
            if (_currentUserService.UserId == null)
                throw new AppException("User id is null");
            if (!Guid.TryParse(_currentUserService.UserId, out userId))
                throw new AppException("User id is wrong");
        }
        var user = await _userManager.FindByIdAsync(userId.ToString());
        if (user == null)
            throw new AppException("User not found", ApiResultStatusCode.NotFound);

        var marketer = await _repositoryWrapper.SetRepository<Marketer>()
            .TableNoTracking
            .FirstOrDefaultAsync(m => m.UserId == user.Id, cancellationToken);

        if (marketer == null)
            throw new AppException("Marketer not found", ApiResultStatusCode.NotFound);
        var foundedDiscount = await _repositoryWrapper.SetRepository<Discount>()
            .TableNoTracking
            .FirstOrDefaultAsync(d => d.IsForSaleCooperation && d.MarketerId == marketer.Id, cancellationToken);
        if (foundedDiscount == null)
        {
            var setting = await _settingService.GetSettingAsync(nameof(MarketerSetting), cancellationToken);
            int discountPercent = 10;
            if (setting is MarketerSetting marketerSetting)
                discountPercent = marketerSetting.DiscountPercent;

            var code = StringExtensions.GetId();
            foundedDiscount = Discount.Create(code, $"کد مخصوص همکاری در فروش برای کاربر - {user.FirstName} {user.LastName}", discountPercent, 0, true,
                DiscountAmountType.Percent, DiscountType.All, 0, true, DateTime.Today, DateTime.Today.AddYears(10), 0,
                false, 0, false, true, 0, false, false, false);
            foundedDiscount.SetCorporate(marketer.Id);

            _repositoryWrapper.SetRepository<Discount>().Add(foundedDiscount);
            await _repositoryWrapper.SaveChangesAsync(cancellationToken);
            return foundedDiscount.Code;

        }
        else
            return foundedDiscount.Code;
    }
}