namespace Netina.Core.EntityServices.MarketerHandlers;

public class SignUpMarketerCommandHandler : IRequestHandler<SignUpMarketerCommand,MarketerProfileResponseDto>
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly IMediator _mediator;
    private readonly ICurrentUserService _currentUserService;
    private readonly IRepositoryWrapper _repositoryWrapper;

    public SignUpMarketerCommandHandler(UserManager<ApplicationUser> userManager,IMediator mediator,ICurrentUserService currentUserService,IRepositoryWrapper repositoryWrapper)
    {
        _userManager = userManager;
        _mediator = mediator;
        _currentUserService = currentUserService;
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<MarketerProfileResponseDto> Handle(SignUpMarketerCommand request, CancellationToken cancellationToken)
    {

        if (_currentUserService.UserId == null)
            throw new AppException("User id is null");
        if (!Guid.TryParse(_currentUserService.UserId, out Guid userId))
            throw new AppException("User id is wrong");

        var user = await _userManager.FindByIdAsync(_currentUserService.UserId);
        if (user == null)
            throw new AppException("User not found");

        var marketer = await _repositoryWrapper.SetRepository<Marketer>()
            .TableNoTracking
            .FirstOrDefaultAsync(m => m.UserId == userId, cancellationToken);
        if (marketer != null)
            return await _mediator.Send(new GetMarketerProfileQuery(MarketerId: marketer.Id), cancellationToken);

        marketer = new Marketer
        {
            UserId = user.Id,
            FatherName = request.FatherName,
            Shaba = request.Shaba,
        };
        _repositoryWrapper.SetRepository<Marketer>()
            .Add(marketer);
        await _repositoryWrapper.SaveChangesAsync(cancellationToken);

        user.BirthDate = DateTimeExtensions.UnixTimeStampToDateTime(request.BirthDate);
        user.NationalId = request.NationalId;
        await _userManager.UpdateAsync(user);

        await _mediator.Send(new CreateMarketerDiscountCommand(userId), cancellationToken);

        return await _mediator.Send(new GetMarketerProfileQuery(marketer.Id), cancellationToken);
    }
}