namespace Brizco.Repository.Handlers.Complex;

public class CreateComplexCommandHandler : IRequestHandler<CreateComplexCommand, ComplexSDto>
{
    private readonly IRepositoryWrapper _repositoryWrapper;
    private readonly ICurrentUserService _currentUserService;

    public CreateComplexCommandHandler(IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService)
    {
        _repositoryWrapper = repositoryWrapper;
        _currentUserService = currentUserService;
    }

    public async Task<ComplexSDto> Handle(CreateComplexCommand request, CancellationToken cancellationToken)
    {
        try
        {
            await _repositoryWrapper.BeginTransaction(cancellationToken);
            var complex = Domain.Entities.Complex.Complex.Create(request.Name, request.Address, request.SupportPhone);
            _repositoryWrapper.SetRepository<Domain.Entities.Complex.Complex>().Add(complex);
            await _repositoryWrapper.SaveChangesAsync(cancellationToken);
            await _repositoryWrapper.CommitAsync(cancellationToken);
            return complex.AdaptToSDto();
        }
        catch (Exception)
        {
            await _repositoryWrapper.RollBackAsync(cancellationToken);
            throw;
        }
    }
}