namespace Netina.Core.EntityServices.MarketerHandlers;

public class SignUpMarketerCommandHandler(
    UserManager<ApplicationUser> userManager,
    IMediator mediator,
    ICurrentUserService currentUserService,
    IRepositoryWrapper repositoryWrapper)
    : IRequestHandler<SignUpMarketerCommand, MarketerProfileResponseDto>
{
    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);
    }
}