namespace Brizco.Repository.Handlers.Position;

public class UpdatePositionCommandHandler : IRequestHandler<UpdatePositionCommand, bool>
{
    private readonly IRepositoryWrapper _repositoryWrapper;
    private readonly ICurrentUserService _currentUserService;

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

    public async Task<bool> Handle(UpdatePositionCommand request, CancellationToken cancellationToken)
    {
        var shift = await _repositoryWrapper.SetRepository<Domain.Entities.Complex.Position>()
            .TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken);
        if (shift == null)
            throw new AppException("Postion not found", ApiResultStatusCode.NotFound);

        if (_currentUserService.ComplexId == null)
            throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
        if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId))
            throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound);

        var newPosition = Domain.Entities.Complex.Position.Create(request.Title,
            request.Description,
            complexId,
            request.SectionId);
        newPosition.Id = request.Id;

        _repositoryWrapper.SetRepository<Domain.Entities.Complex.Position>()
            .Update(newPosition);

        await _repositoryWrapper.SaveChangesAsync(cancellationToken);

        return true;
    }
}