public async Task <IActionResult> CloneHearing([FromRoute] Guid hearingId,
                                                       [FromBody] CloneHearingRequest request)
        {
            var getHearingByIdQuery = new GetHearingByIdQuery(hearingId);
            var videoHearing        = await _queryHandler.Handle <GetHearingByIdQuery, VideoHearing>(getHearingByIdQuery);

            if (videoHearing == null)
            {
                return(NotFound());
            }

            var validationResult =
                new CloneHearingRequestValidation(videoHearing)
                .ValidateDates(request);

            if (!validationResult.IsValid)
            {
                ModelState.AddFluentValidationErrors(validationResult.Errors);
                return(BadRequest(ModelState));
            }

            var orderedDates = request.Dates.OrderBy(x => x).ToList();
            var totalDays    = orderedDates.Count + 1; // include original hearing
            var commands     = orderedDates.Select((newDate, index) =>
            {
                var hearingDay = index + 2; // zero index including original hearing
                return(CloneHearingToCommandMapper.CloneToCommand(videoHearing, newDate, _randomGenerator,
                                                                  _kinlyConfiguration.SipAddressStem, totalDays, hearingDay));
            }).ToList();

            foreach (var command in commands)
            {
                // dbcontext is not thread safe. loop one at a time
                await _commandHandler.Handle(command);
            }

            var existingCase = videoHearing.GetCases().First();
            await _hearingService.UpdateHearingCaseName(hearingId, $"{existingCase.Name} Day {1} of {totalDays}");

            return(NoContent());
        }
        public async Task CloneVideoHearing(Guid hearingId, IList <DateTime> datesOfHearing)
        {
            var dbContext = new BookingsDbContext(_dbContextOptions);
            var hearing   = await new GetHearingByIdQueryHandler(dbContext)
                            .Handle(new GetHearingByIdQuery(hearingId));

            var orderedDates = datesOfHearing.OrderBy(x => x).ToList();
            var totalDays    = orderedDates.Count + 1;
            var commands     = orderedDates.Select((newDate, index) =>
            {
                var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                             .AddJsonFile("appsettings.json")
                             .Build();
                var hearingDay = index + 2;
                return(CloneHearingToCommandMapper.CloneToCommand(hearing, newDate, new RandomGenerator(),
                                                                  config.GetValue <string>("KinlyConfiguration:SipAddressStem"), totalDays, hearingDay));
            }).ToList();

            foreach (var command in commands)
            {
                await new CreateVideoHearingCommandHandler(dbContext, new HearingService(dbContext)).Handle(command);
            }
        }
        public void should_map_hearing_to_command()
        {
            var totalDays  = 5;
            var hearingDay = 2;
            var hearing    = new VideoHearingBuilder().Build();

            hearing.AddEndpoint(new Endpoint("Endpoint1", $"{Guid.NewGuid():N}@hmcts.net", "1234", null));
            hearing.AddEndpoint(new Endpoint("Endpoint2", $"{Guid.NewGuid():N}@hmcts.net", "2345",
                                             hearing.GetParticipants().First(x => x.HearingRole.UserRole.IsRepresentative)));
            hearing.AddCase("HBS/1234", "Case 1 Test", true);

            var individualsInHearing = hearing.Participants.Where(x => x.HearingRole.UserRole.IsIndividual).ToList();

            individualsInHearing[0].AddLink(individualsInHearing[1].Id, LinkedParticipantType.Interpreter);
            individualsInHearing[1].AddLink(individualsInHearing[0].Id, LinkedParticipantType.Interpreter);

            var newDate = hearing.ScheduledDateTime.AddDays(1);

            var command = CloneHearingToCommandMapper.CloneToCommand(hearing, newDate, _randomGenerator,
                                                                     _sipAddressStem, totalDays, hearingDay);

            command.HearingRoomName.Should().Be(hearing.HearingRoomName);
            command.OtherInformation.Should().Be(hearing.OtherInformation);
            command.CreatedBy.Should().Be(hearing.CreatedBy);

            command.CaseType.Should().Be(hearing.CaseType);
            command.HearingType.Should().Be(hearing.HearingType);

            command.ScheduledDateTime.Should().Be(newDate);
            command.ScheduledDateTime.Hour.Should().Be(hearing.ScheduledDateTime.Hour);
            command.ScheduledDateTime.Minute.Should().Be(hearing.ScheduledDateTime.Minute);
            command.ScheduledDuration.Should().Be(480);

            command.Venue.Should().Be(hearing.HearingVenue);

            command.Participants.Count.Should().Be(hearing.GetParticipants().Count);
            foreach (var newParticipant in command.Participants)
            {
                var existingPerson = hearing.GetPersons().SingleOrDefault(x => x.Username == newParticipant.Person.Username);
                existingPerson.Should().NotBeNull();
                var existingPat = hearing.Participants.Single(x => x.Person == existingPerson);
                newParticipant.DisplayName.Should().Be(existingPat.DisplayName);
                newParticipant.CaseRole.Should().Be(existingPat.CaseRole);
                newParticipant.HearingRole.Should().Be(existingPat.HearingRole);

                if (existingPat.GetType() != typeof(Representative))
                {
                    continue;
                }
                var rep = (Representative)existingPat;
                newParticipant.Representee.Should().Be(rep.Representee);
            }

            command.Cases.Count.Should().Be(hearing.GetCases().Count);
            foreach (var @case in command.Cases)
            {
                hearing.GetCases().SingleOrDefault(x => x.Number == @case.Number).Should()
                .NotBeNull();
                @case.Name.Should().Contain($"Day {hearingDay} of {totalDays}");
            }

            command.Endpoints.Count.Should().Be(hearing.GetEndpoints().Count);
            foreach (var ep in command.Endpoints)
            {
                hearing.GetEndpoints().SingleOrDefault(x =>
                                                       x.DisplayName == ep.DisplayName &&
                                                       x.DefenceAdvocate?.Person?.Username == ep.DefenceAdvocateUsername).Should().NotBeNull();
            }

            command.QuestionnaireNotRequired.Should().BeTrue();
            command.AudioRecordingRequired.Should().Be(hearing.AudioRecordingRequired);
        }