using Microsoft.EntityFrameworkCore;

namespace NetinaShop.Repository.Handlers.Discounts;

public class CreateSaleCooperationDiscountHandler : IRequestHandler<CreateSaleCooperationDiscount,string>
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly IRepositoryWrapper _repositoryWrapper;
    private readonly ICurrentUserService _currentUserService;

    public CreateSaleCooperationDiscountHandler(UserManager<ApplicationUser> userManager,IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService)
    {
        _userManager = userManager;
        _repositoryWrapper = repositoryWrapper;
        _currentUserService = currentUserService;
    }
    public async Task<string> Handle(CreateSaleCooperationDiscount request, CancellationToken cancellationToken)
    {
        var userId = request.CorporateUserId;
        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(request.CorporateUserId.ToString());
        if (user == null)
            throw new AppException("User not found", ApiResultStatusCode.NotFound);

        var foundedDiscount = await _repositoryWrapper.SetRepository<Discount>()
            .TableNoTracking
            .FirstOrDefaultAsync(d => d.IsForSaleCooperation && d.CorporateUserId == userId, cancellationToken);
        if (foundedDiscount == null)
        {
            var code = StringExtensions.GetId();
            foundedDiscount = Discount.Create(code,$"کد مخصوص همکاری در فروش برای کاربر - {user.FirstName} {user.LastName}", 10, 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(userId);

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

        }
        else
            return foundedDiscount.Code;
    }
}