package com.oguerreiro.resilient.web.rest;

import static com.oguerreiro.resilient.domain.PeriodVersionAsserts.assertPeriodVersionAllPropertiesEquals;
import static com.oguerreiro.resilient.domain.PeriodVersionAsserts.assertPeriodVersionAllUpdatablePropertiesEquals;
import static com.oguerreiro.resilient.domain.PeriodVersionAsserts.assertPeriodVersionUpdatableFieldsEquals;
import static com.oguerreiro.resilient.web.rest.TestUtil.createUpdateProxyForBean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.oguerreiro.resilient.IntegrationTest;
import com.oguerreiro.resilient.domain.PeriodVersion;
import com.oguerreiro.resilient.domain.enumeration.PeriodVersionStatus;
import com.oguerreiro.resilient.repository.PeriodVersionRepository;
import com.oguerreiro.resilient.service.PeriodVersionService;
import com.oguerreiro.resilient.service.dto.PeriodVersionDTO;
import com.oguerreiro.resilient.service.mapper.PeriodVersionMapper;

import jakarta.persistence.EntityManager;

/**
 * Integration tests for the {@link PeriodVersionResource} REST controller.
 */
@IntegrationTest
@ExtendWith(MockitoExtension.class)
@AutoConfigureMockMvc
@WithMockUser
class PeriodVersionResourceIT {

  private static final String DEFAULT_NAME = "AAAAAAAAAA";
  private static final String UPDATED_NAME = "BBBBBBBBBB";

  private static final String DEFAULT_DESCRIPTION = "AAAAAAAAAA";
  private static final String UPDATED_DESCRIPTION = "BBBBBBBBBB";

  private static final Integer DEFAULT_PERIOD_VERSION = 1;
  private static final Integer UPDATED_PERIOD_VERSION = 2;

  private static final PeriodVersionStatus DEFAULT_STATE = PeriodVersionStatus.PROCESSING;
  private static final PeriodVersionStatus UPDATED_STATE = PeriodVersionStatus.ENDED;

  private static final Instant DEFAULT_CREATION_DATE = Instant.ofEpochMilli(0L);
  private static final Instant UPDATED_CREATION_DATE = Instant.now().truncatedTo(ChronoUnit.MILLIS);

  private static final String DEFAULT_CREATION_USERNAME = "AAAAAAAAAA";
  private static final String UPDATED_CREATION_USERNAME = "BBBBBBBBBB";

  private static final Integer DEFAULT_VERSION = 1;
  private static final Integer UPDATED_VERSION = 2;

  private static final String ENTITY_API_URL = "/api/period-versions";
  private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}";

  private static Random random = new Random();
  private static AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE));

  @Autowired
  private ObjectMapper om;

  @Autowired
  private PeriodVersionRepository periodVersionRepository;

  @Mock
  private PeriodVersionRepository periodVersionRepositoryMock;

  @Autowired
  private PeriodVersionMapper periodVersionMapper;

  @Mock
  private PeriodVersionService periodVersionServiceMock;

  @Autowired
  private EntityManager em;

  @Autowired
  private MockMvc restPeriodVersionMockMvc;

  private PeriodVersion periodVersion;

  private PeriodVersion insertedPeriodVersion;

  /**
   * Create an entity for this test.
   *
   * This is a static method, as tests for other entities might also need it, if
   * they test an entity which requires the current entity.
   */
  public static PeriodVersion createEntity(EntityManager em) {
    PeriodVersion periodVersion = new PeriodVersion().name(DEFAULT_NAME).description(DEFAULT_DESCRIPTION)
        .periodVersion(DEFAULT_PERIOD_VERSION).state(DEFAULT_STATE).creationDate(DEFAULT_CREATION_DATE)
        .creationUsername(DEFAULT_CREATION_USERNAME).version(DEFAULT_VERSION);
    return periodVersion;
  }

  /**
   * Create an updated entity for this test.
   *
   * This is a static method, as tests for other entities might also need it, if
   * they test an entity which requires the current entity.
   */
  public static PeriodVersion createUpdatedEntity(EntityManager em) {
    PeriodVersion periodVersion = new PeriodVersion().name(UPDATED_NAME).description(UPDATED_DESCRIPTION)
        .periodVersion(UPDATED_PERIOD_VERSION).state(UPDATED_STATE).creationDate(UPDATED_CREATION_DATE)
        .creationUsername(UPDATED_CREATION_USERNAME).version(UPDATED_VERSION);
    return periodVersion;
  }

  @BeforeEach
  public void initTest() {
    periodVersion = createEntity(em);
  }

  @AfterEach
  public void cleanup() {
    if (insertedPeriodVersion != null) {
      periodVersionRepository.delete(insertedPeriodVersion);
      insertedPeriodVersion = null;
    }
  }

  @Test
  @Transactional
  void createPeriodVersion() throws Exception {
    long databaseSizeBeforeCreate = getRepositoryCount();
    // Create the PeriodVersion
    PeriodVersionDTO periodVersionDTO = periodVersionMapper.toDto(periodVersion);
    var returnedPeriodVersionDTO = om.readValue(restPeriodVersionMockMvc
        .perform(post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON)
            .content(om.writeValueAsBytes(periodVersionDTO)))
        .andExpect(status().isCreated()).andReturn().getResponse().getContentAsString(), PeriodVersionDTO.class);

    // Validate the PeriodVersion in the database
    assertIncrementedRepositoryCount(databaseSizeBeforeCreate);
    var returnedPeriodVersion = periodVersionMapper.toEntity(returnedPeriodVersionDTO);
    assertPeriodVersionUpdatableFieldsEquals(returnedPeriodVersion, getPersistedPeriodVersion(returnedPeriodVersion));

    insertedPeriodVersion = returnedPeriodVersion;
  }

  @Test
  @Transactional
  void createPeriodVersionWithExistingId() throws Exception {
    // Create the PeriodVersion with an existing ID
    periodVersion.setId(1L);
    PeriodVersionDTO periodVersionDTO = periodVersionMapper.toDto(periodVersion);

    long databaseSizeBeforeCreate = getRepositoryCount();

    // An entity with an existing ID cannot be created, so this API call must fail
    restPeriodVersionMockMvc.perform(post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON)
        .content(om.writeValueAsBytes(periodVersionDTO))).andExpect(status().isBadRequest());

    // Validate the PeriodVersion in the database
    assertSameRepositoryCount(databaseSizeBeforeCreate);
  }

  @Test
  @Transactional
  void checkNameIsRequired() throws Exception {
    long databaseSizeBeforeTest = getRepositoryCount();
    // set the field null
    periodVersion.setName(null);

    // Create the PeriodVersion, which fails.
    PeriodVersionDTO periodVersionDTO = periodVersionMapper.toDto(periodVersion);

    restPeriodVersionMockMvc.perform(post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON)
        .content(om.writeValueAsBytes(periodVersionDTO))).andExpect(status().isBadRequest());

    assertSameRepositoryCount(databaseSizeBeforeTest);
  }

  @Test
  @Transactional
  void checkPeriodVersionIsRequired() throws Exception {
    long databaseSizeBeforeTest = getRepositoryCount();
    // set the field null
    periodVersion.setPeriodVersion(null);

    // Create the PeriodVersion, which fails.
    PeriodVersionDTO periodVersionDTO = periodVersionMapper.toDto(periodVersion);

    restPeriodVersionMockMvc.perform(post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON)
        .content(om.writeValueAsBytes(periodVersionDTO))).andExpect(status().isBadRequest());

    assertSameRepositoryCount(databaseSizeBeforeTest);
  }

  @Test
  @Transactional
  void checkStateIsRequired() throws Exception {
    long databaseSizeBeforeTest = getRepositoryCount();
    // set the field null
    periodVersion.setState(null);

    // Create the PeriodVersion, which fails.
    PeriodVersionDTO periodVersionDTO = periodVersionMapper.toDto(periodVersion);

    restPeriodVersionMockMvc.perform(post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON)
        .content(om.writeValueAsBytes(periodVersionDTO))).andExpect(status().isBadRequest());

    assertSameRepositoryCount(databaseSizeBeforeTest);
  }

  @Test
  @Transactional
  void checkCreationDateIsRequired() throws Exception {
    long databaseSizeBeforeTest = getRepositoryCount();
    // set the field null
    periodVersion.setCreationDate(null);

    // Create the PeriodVersion, which fails.
    PeriodVersionDTO periodVersionDTO = periodVersionMapper.toDto(periodVersion);

    restPeriodVersionMockMvc.perform(post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON)
        .content(om.writeValueAsBytes(periodVersionDTO))).andExpect(status().isBadRequest());

    assertSameRepositoryCount(databaseSizeBeforeTest);
  }

  @Test
  @Transactional
  void checkCreationUsernameIsRequired() throws Exception {
    long databaseSizeBeforeTest = getRepositoryCount();
    // set the field null
    periodVersion.setCreationUsername(null);

    // Create the PeriodVersion, which fails.
    PeriodVersionDTO periodVersionDTO = periodVersionMapper.toDto(periodVersion);

    restPeriodVersionMockMvc.perform(post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON)
        .content(om.writeValueAsBytes(periodVersionDTO))).andExpect(status().isBadRequest());

    assertSameRepositoryCount(databaseSizeBeforeTest);
  }

  @Test
  @Transactional
  void getAllPeriodVersions() throws Exception {
    // Initialize the database
    insertedPeriodVersion = periodVersionRepository.saveAndFlush(periodVersion);

    // Get all the periodVersionList
    restPeriodVersionMockMvc.perform(get(ENTITY_API_URL + "?sort=id,desc")).andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
        .andExpect(jsonPath("$.[*].id").value(hasItem(periodVersion.getId().intValue())))
        .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME)))
        .andExpect(jsonPath("$.[*].description").value(hasItem(DEFAULT_DESCRIPTION)))
        .andExpect(jsonPath("$.[*].periodVersion").value(hasItem(DEFAULT_PERIOD_VERSION)))
        .andExpect(jsonPath("$.[*].state").value(hasItem(DEFAULT_STATE.toString())))
        .andExpect(jsonPath("$.[*].creationDate").value(hasItem(DEFAULT_CREATION_DATE.toString())))
        .andExpect(jsonPath("$.[*].creationUsername").value(hasItem(DEFAULT_CREATION_USERNAME)))
        .andExpect(jsonPath("$.[*].version").value(hasItem(DEFAULT_VERSION)));
  }

  @SuppressWarnings({ "unchecked" })
  void getAllPeriodVersionsWithEagerRelationshipsIsEnabled() throws Exception {
    when(periodVersionServiceMock.findAllWithEagerRelationships(any())).thenReturn(new PageImpl(new ArrayList<>()));

    restPeriodVersionMockMvc.perform(get(ENTITY_API_URL + "?eagerload=true")).andExpect(status().isOk());

    verify(periodVersionServiceMock, times(1)).findAllWithEagerRelationships(any());
  }

  @SuppressWarnings({ "unchecked" })
  void getAllPeriodVersionsWithEagerRelationshipsIsNotEnabled() throws Exception {
    when(periodVersionServiceMock.findAllWithEagerRelationships(any())).thenReturn(new PageImpl(new ArrayList<>()));

    restPeriodVersionMockMvc.perform(get(ENTITY_API_URL + "?eagerload=false")).andExpect(status().isOk());
    verify(periodVersionRepositoryMock, times(1)).findAll(any(Pageable.class));
  }

  @Test
  @Transactional
  void getPeriodVersion() throws Exception {
    // Initialize the database
    insertedPeriodVersion = periodVersionRepository.saveAndFlush(periodVersion);

    // Get the periodVersion
    restPeriodVersionMockMvc.perform(get(ENTITY_API_URL_ID, periodVersion.getId())).andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
        .andExpect(jsonPath("$.id").value(periodVersion.getId().intValue()))
        .andExpect(jsonPath("$.name").value(DEFAULT_NAME))
        .andExpect(jsonPath("$.description").value(DEFAULT_DESCRIPTION))
        .andExpect(jsonPath("$.periodVersion").value(DEFAULT_PERIOD_VERSION))
        .andExpect(jsonPath("$.state").value(DEFAULT_STATE.toString()))
        .andExpect(jsonPath("$.creationDate").value(DEFAULT_CREATION_DATE.toString()))
        .andExpect(jsonPath("$.creationUsername").value(DEFAULT_CREATION_USERNAME))
        .andExpect(jsonPath("$.version").value(DEFAULT_VERSION));
  }

  @Test
  @Transactional
  void getNonExistingPeriodVersion() throws Exception {
    // Get the periodVersion
    restPeriodVersionMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound());
  }

  @Test
  @Transactional
  void putExistingPeriodVersion() throws Exception {
    // Initialize the database
    insertedPeriodVersion = periodVersionRepository.saveAndFlush(periodVersion);

    long databaseSizeBeforeUpdate = getRepositoryCount();

    // Update the periodVersion
    PeriodVersion updatedPeriodVersion = periodVersionRepository.findById(periodVersion.getId()).orElseThrow();
    // Disconnect from session so that the updates on updatedPeriodVersion are not
    // directly saved in db
    em.detach(updatedPeriodVersion);
    updatedPeriodVersion.name(UPDATED_NAME).description(UPDATED_DESCRIPTION).periodVersion(UPDATED_PERIOD_VERSION)
        .state(UPDATED_STATE).creationDate(UPDATED_CREATION_DATE).creationUsername(UPDATED_CREATION_USERNAME)
        .version(UPDATED_VERSION);
    PeriodVersionDTO periodVersionDTO = periodVersionMapper.toDto(updatedPeriodVersion);

    restPeriodVersionMockMvc.perform(put(ENTITY_API_URL_ID, periodVersionDTO.getId()).with(csrf())
        .contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(periodVersionDTO)))
        .andExpect(status().isOk());

    // Validate the PeriodVersion in the database
    assertSameRepositoryCount(databaseSizeBeforeUpdate);
    assertPersistedPeriodVersionToMatchAllProperties(updatedPeriodVersion);
  }

  @Test
  @Transactional
  void putNonExistingPeriodVersion() throws Exception {
    long databaseSizeBeforeUpdate = getRepositoryCount();
    periodVersion.setId(longCount.incrementAndGet());

    // Create the PeriodVersion
    PeriodVersionDTO periodVersionDTO = periodVersionMapper.toDto(periodVersion);

    // If the entity doesn't have an ID, it will throw BadRequestAlertException
    restPeriodVersionMockMvc.perform(put(ENTITY_API_URL_ID, periodVersionDTO.getId()).with(csrf())
        .contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(periodVersionDTO)))
        .andExpect(status().isBadRequest());

    // Validate the PeriodVersion in the database
    assertSameRepositoryCount(databaseSizeBeforeUpdate);
  }

  @Test
  @Transactional
  void putWithIdMismatchPeriodVersion() throws Exception {
    long databaseSizeBeforeUpdate = getRepositoryCount();
    periodVersion.setId(longCount.incrementAndGet());

    // Create the PeriodVersion
    PeriodVersionDTO periodVersionDTO = periodVersionMapper.toDto(periodVersion);

    // If url ID doesn't match entity ID, it will throw BadRequestAlertException
    restPeriodVersionMockMvc
        .perform(put(ENTITY_API_URL_ID, longCount.incrementAndGet()).with(csrf())
            .contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(periodVersionDTO)))
        .andExpect(status().isBadRequest());

    // Validate the PeriodVersion in the database
    assertSameRepositoryCount(databaseSizeBeforeUpdate);
  }

  @Test
  @Transactional
  void putWithMissingIdPathParamPeriodVersion() throws Exception {
    long databaseSizeBeforeUpdate = getRepositoryCount();
    periodVersion.setId(longCount.incrementAndGet());

    // Create the PeriodVersion
    PeriodVersionDTO periodVersionDTO = periodVersionMapper.toDto(periodVersion);

    // If url ID doesn't match entity ID, it will throw BadRequestAlertException
    restPeriodVersionMockMvc.perform(put(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON)
        .content(om.writeValueAsBytes(periodVersionDTO))).andExpect(status().isMethodNotAllowed());

    // Validate the PeriodVersion in the database
    assertSameRepositoryCount(databaseSizeBeforeUpdate);
  }

  @Test
  @Transactional
  void partialUpdatePeriodVersionWithPatch() throws Exception {
    // Initialize the database
    insertedPeriodVersion = periodVersionRepository.saveAndFlush(periodVersion);

    long databaseSizeBeforeUpdate = getRepositoryCount();

    // Update the periodVersion using partial update
    PeriodVersion partialUpdatedPeriodVersion = new PeriodVersion();
    partialUpdatedPeriodVersion.setId(periodVersion.getId());

    partialUpdatedPeriodVersion.description(UPDATED_DESCRIPTION).state(UPDATED_STATE);

    restPeriodVersionMockMvc
        .perform(patch(ENTITY_API_URL_ID, partialUpdatedPeriodVersion.getId()).with(csrf())
            .contentType("application/merge-patch+json").content(om.writeValueAsBytes(partialUpdatedPeriodVersion)))
        .andExpect(status().isOk());

    // Validate the PeriodVersion in the database

    assertSameRepositoryCount(databaseSizeBeforeUpdate);
    assertPeriodVersionUpdatableFieldsEquals(createUpdateProxyForBean(partialUpdatedPeriodVersion, periodVersion),
        getPersistedPeriodVersion(periodVersion));
  }

  @Test
  @Transactional
  void fullUpdatePeriodVersionWithPatch() throws Exception {
    // Initialize the database
    insertedPeriodVersion = periodVersionRepository.saveAndFlush(periodVersion);

    long databaseSizeBeforeUpdate = getRepositoryCount();

    // Update the periodVersion using partial update
    PeriodVersion partialUpdatedPeriodVersion = new PeriodVersion();
    partialUpdatedPeriodVersion.setId(periodVersion.getId());

    partialUpdatedPeriodVersion.name(UPDATED_NAME).description(UPDATED_DESCRIPTION)
        .periodVersion(UPDATED_PERIOD_VERSION).state(UPDATED_STATE).creationDate(UPDATED_CREATION_DATE)
        .creationUsername(UPDATED_CREATION_USERNAME).version(UPDATED_VERSION);

    restPeriodVersionMockMvc
        .perform(patch(ENTITY_API_URL_ID, partialUpdatedPeriodVersion.getId()).with(csrf())
            .contentType("application/merge-patch+json").content(om.writeValueAsBytes(partialUpdatedPeriodVersion)))
        .andExpect(status().isOk());

    // Validate the PeriodVersion in the database

    assertSameRepositoryCount(databaseSizeBeforeUpdate);
    assertPeriodVersionUpdatableFieldsEquals(partialUpdatedPeriodVersion,
        getPersistedPeriodVersion(partialUpdatedPeriodVersion));
  }

  @Test
  @Transactional
  void patchNonExistingPeriodVersion() throws Exception {
    long databaseSizeBeforeUpdate = getRepositoryCount();
    periodVersion.setId(longCount.incrementAndGet());

    // Create the PeriodVersion
    PeriodVersionDTO periodVersionDTO = periodVersionMapper.toDto(periodVersion);

    // If the entity doesn't have an ID, it will throw BadRequestAlertException
    restPeriodVersionMockMvc
        .perform(patch(ENTITY_API_URL_ID, periodVersionDTO.getId()).with(csrf())
            .contentType("application/merge-patch+json").content(om.writeValueAsBytes(periodVersionDTO)))
        .andExpect(status().isBadRequest());

    // Validate the PeriodVersion in the database
    assertSameRepositoryCount(databaseSizeBeforeUpdate);
  }

  @Test
  @Transactional
  void patchWithIdMismatchPeriodVersion() throws Exception {
    long databaseSizeBeforeUpdate = getRepositoryCount();
    periodVersion.setId(longCount.incrementAndGet());

    // Create the PeriodVersion
    PeriodVersionDTO periodVersionDTO = periodVersionMapper.toDto(periodVersion);

    // If url ID doesn't match entity ID, it will throw BadRequestAlertException
    restPeriodVersionMockMvc
        .perform(patch(ENTITY_API_URL_ID, longCount.incrementAndGet()).with(csrf())
            .contentType("application/merge-patch+json").content(om.writeValueAsBytes(periodVersionDTO)))
        .andExpect(status().isBadRequest());

    // Validate the PeriodVersion in the database
    assertSameRepositoryCount(databaseSizeBeforeUpdate);
  }

  @Test
  @Transactional
  void patchWithMissingIdPathParamPeriodVersion() throws Exception {
    long databaseSizeBeforeUpdate = getRepositoryCount();
    periodVersion.setId(longCount.incrementAndGet());

    // Create the PeriodVersion
    PeriodVersionDTO periodVersionDTO = periodVersionMapper.toDto(periodVersion);

    // If url ID doesn't match entity ID, it will throw BadRequestAlertException
    restPeriodVersionMockMvc.perform(patch(ENTITY_API_URL).with(csrf()).contentType("application/merge-patch+json")
        .content(om.writeValueAsBytes(periodVersionDTO))).andExpect(status().isMethodNotAllowed());

    // Validate the PeriodVersion in the database
    assertSameRepositoryCount(databaseSizeBeforeUpdate);
  }

  @Test
  @Transactional
  void deletePeriodVersion() throws Exception {
    // Initialize the database
    insertedPeriodVersion = periodVersionRepository.saveAndFlush(periodVersion);

    long databaseSizeBeforeDelete = getRepositoryCount();

    // Delete the periodVersion
    restPeriodVersionMockMvc
        .perform(delete(ENTITY_API_URL_ID, periodVersion.getId()).with(csrf()).accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isNoContent());

    // Validate the database contains one less item
    assertDecrementedRepositoryCount(databaseSizeBeforeDelete);
  }

  protected long getRepositoryCount() {
    return periodVersionRepository.count();
  }

  protected void assertIncrementedRepositoryCount(long countBefore) {
    assertThat(countBefore + 1).isEqualTo(getRepositoryCount());
  }

  protected void assertDecrementedRepositoryCount(long countBefore) {
    assertThat(countBefore - 1).isEqualTo(getRepositoryCount());
  }

  protected void assertSameRepositoryCount(long countBefore) {
    assertThat(countBefore).isEqualTo(getRepositoryCount());
  }

  protected PeriodVersion getPersistedPeriodVersion(PeriodVersion periodVersion) {
    return periodVersionRepository.findById(periodVersion.getId()).orElseThrow();
  }

  protected void assertPersistedPeriodVersionToMatchAllProperties(PeriodVersion expectedPeriodVersion) {
    assertPeriodVersionAllPropertiesEquals(expectedPeriodVersion, getPersistedPeriodVersion(expectedPeriodVersion));
  }

  protected void assertPersistedPeriodVersionToMatchUpdatableProperties(PeriodVersion expectedPeriodVersion) {
    assertPeriodVersionAllUpdatablePropertiesEquals(expectedPeriodVersion,
        getPersistedPeriodVersion(expectedPeriodVersion));
  }
}
