package com.oguerreiro.resilient.web.rest;

import static com.oguerreiro.resilient.domain.InputDataAsserts.*;
import static com.oguerreiro.resilient.web.rest.TestUtil.createUpdateProxyForBean;
import static com.oguerreiro.resilient.web.rest.TestUtil.sameNumber;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.mockito.Mockito.*;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.oguerreiro.resilient.IntegrationTest;
import com.oguerreiro.resilient.domain.InputData;
import com.oguerreiro.resilient.domain.enumeration.DataSourceType;
import com.oguerreiro.resilient.repository.InputDataRepository;
import com.oguerreiro.resilient.service.InputDataService;
import com.oguerreiro.resilient.service.dto.InputDataDTO;
import com.oguerreiro.resilient.service.mapper.InputDataMapper;
import jakarta.persistence.EntityManager;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
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;

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

    private static final BigDecimal DEFAULT_SOURCE_VALUE = new BigDecimal(1);
    private static final BigDecimal UPDATED_SOURCE_VALUE = new BigDecimal(2);

    private static final BigDecimal DEFAULT_VARIABLE_VALUE = new BigDecimal(1);
    private static final BigDecimal UPDATED_VARIABLE_VALUE = new BigDecimal(2);

    private static final BigDecimal DEFAULT_IMPUTED_VALUE = new BigDecimal(1);
    private static final BigDecimal UPDATED_IMPUTED_VALUE = new BigDecimal(2);

    private static final DataSourceType DEFAULT_SOURCE_TYPE = DataSourceType.MANUAL;
    private static final DataSourceType UPDATED_SOURCE_TYPE = DataSourceType.FILE;

    private static final LocalDate DEFAULT_DATA_DATE = LocalDate.ofEpochDay(0L);
    private static final LocalDate UPDATED_DATA_DATE = LocalDate.now(ZoneId.systemDefault());

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

    private static final String DEFAULT_CHANGE_USERNAME = "AAAAAAAAAA";
    private static final String UPDATED_CHANGE_USERNAME = "BBBBBBBBBB";

    private static final String DEFAULT_DATA_SOURCE = "AAAAAAAAAA";
    private static final String UPDATED_DATA_SOURCE = "BBBBBBBBBB";

    private static final String DEFAULT_DATA_USER = "AAAAAAAAAA";
    private static final String UPDATED_DATA_USER = "BBBBBBBBBB";

    private static final String DEFAULT_DATA_COMMENTS = "AAAAAAAAAA";
    private static final String UPDATED_DATA_COMMENTS = "BBBBBBBBBB";

    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/input-data";
    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 InputDataRepository inputDataRepository;

    @Mock
    private InputDataRepository inputDataRepositoryMock;

    @Autowired
    private InputDataMapper inputDataMapper;

    @Mock
    private InputDataService inputDataServiceMock;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restInputDataMockMvc;

    private InputData inputData;

    private InputData insertedInputData;

    /**
     * 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 InputData createEntity(EntityManager em) {
        InputData inputData = new InputData()
            .sourceValue(DEFAULT_SOURCE_VALUE)
            .variableValue(DEFAULT_VARIABLE_VALUE)
            .imputedValue(DEFAULT_IMPUTED_VALUE)
            .sourceType(DEFAULT_SOURCE_TYPE)
            .dataDate(DEFAULT_DATA_DATE)
            .changeDate(DEFAULT_CHANGE_DATE)
            .changeUsername(DEFAULT_CHANGE_USERNAME)
            .dataSource(DEFAULT_DATA_SOURCE)
            .dataUser(DEFAULT_DATA_USER)
            .dataComments(DEFAULT_DATA_COMMENTS)
            .creationDate(DEFAULT_CREATION_DATE)
            .creationUsername(DEFAULT_CREATION_USERNAME)
            .version(DEFAULT_VERSION);
        return inputData;
    }

    /**
     * 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 InputData createUpdatedEntity(EntityManager em) {
        InputData inputData = new InputData()
            .sourceValue(UPDATED_SOURCE_VALUE)
            .variableValue(UPDATED_VARIABLE_VALUE)
            .imputedValue(UPDATED_IMPUTED_VALUE)
            .sourceType(UPDATED_SOURCE_TYPE)
            .dataDate(UPDATED_DATA_DATE)
            .changeDate(UPDATED_CHANGE_DATE)
            .changeUsername(UPDATED_CHANGE_USERNAME)
            .dataSource(UPDATED_DATA_SOURCE)
            .dataUser(UPDATED_DATA_USER)
            .dataComments(UPDATED_DATA_COMMENTS)
            .creationDate(UPDATED_CREATION_DATE)
            .creationUsername(UPDATED_CREATION_USERNAME)
            .version(UPDATED_VERSION);
        return inputData;
    }

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

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

    @Test
    @Transactional
    void createInputData() throws Exception {
        long databaseSizeBeforeCreate = getRepositoryCount();
        // Create the InputData
        InputDataDTO inputDataDTO = inputDataMapper.toDto(inputData);
        var returnedInputDataDTO = om.readValue(
            restInputDataMockMvc
                .perform(
                    post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(inputDataDTO))
                )
                .andExpect(status().isCreated())
                .andReturn()
                .getResponse()
                .getContentAsString(),
            InputDataDTO.class
        );

        // Validate the InputData in the database
        assertIncrementedRepositoryCount(databaseSizeBeforeCreate);
        var returnedInputData = inputDataMapper.toEntity(returnedInputDataDTO);
        assertInputDataUpdatableFieldsEquals(returnedInputData, getPersistedInputData(returnedInputData));

        insertedInputData = returnedInputData;
    }

    @Test
    @Transactional
    void createInputDataWithExistingId() throws Exception {
        // Create the InputData with an existing ID
        inputData.setId(1L);
        InputDataDTO inputDataDTO = inputDataMapper.toDto(inputData);

        long databaseSizeBeforeCreate = getRepositoryCount();

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

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

    @Test
    @Transactional
    void checkSourceValueIsRequired() throws Exception {
        long databaseSizeBeforeTest = getRepositoryCount();
        // set the field null
        inputData.setSourceValue(null);

        // Create the InputData, which fails.
        InputDataDTO inputDataDTO = inputDataMapper.toDto(inputData);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void checkVariableValueIsRequired() throws Exception {
        long databaseSizeBeforeTest = getRepositoryCount();
        // set the field null
        inputData.setVariableValue(null);

        // Create the InputData, which fails.
        InputDataDTO inputDataDTO = inputDataMapper.toDto(inputData);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void checkImputedValueIsRequired() throws Exception {
        long databaseSizeBeforeTest = getRepositoryCount();
        // set the field null
        inputData.setImputedValue(null);

        // Create the InputData, which fails.
        InputDataDTO inputDataDTO = inputDataMapper.toDto(inputData);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void checkSourceTypeIsRequired() throws Exception {
        long databaseSizeBeforeTest = getRepositoryCount();
        // set the field null
        inputData.setSourceType(null);

        // Create the InputData, which fails.
        InputDataDTO inputDataDTO = inputDataMapper.toDto(inputData);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void checkChangeDateIsRequired() throws Exception {
        long databaseSizeBeforeTest = getRepositoryCount();
        // set the field null
        inputData.setChangeDate(null);

        // Create the InputData, which fails.
        InputDataDTO inputDataDTO = inputDataMapper.toDto(inputData);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void checkChangeUsernameIsRequired() throws Exception {
        long databaseSizeBeforeTest = getRepositoryCount();
        // set the field null
        inputData.setChangeUsername(null);

        // Create the InputData, which fails.
        InputDataDTO inputDataDTO = inputDataMapper.toDto(inputData);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

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

        // Create the InputData, which fails.
        InputDataDTO inputDataDTO = inputDataMapper.toDto(inputData);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

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

        // Create the InputData, which fails.
        InputDataDTO inputDataDTO = inputDataMapper.toDto(inputData);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void getAllInputData() throws Exception {
        // Initialize the database
        insertedInputData = inputDataRepository.saveAndFlush(inputData);

        // Get all the inputDataList
        restInputDataMockMvc
            .perform(get(ENTITY_API_URL + "?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(inputData.getId().intValue())))
            .andExpect(jsonPath("$.[*].sourceValue").value(hasItem(sameNumber(DEFAULT_SOURCE_VALUE))))
            .andExpect(jsonPath("$.[*].variableValue").value(hasItem(sameNumber(DEFAULT_VARIABLE_VALUE))))
            .andExpect(jsonPath("$.[*].imputedValue").value(hasItem(sameNumber(DEFAULT_IMPUTED_VALUE))))
            .andExpect(jsonPath("$.[*].sourceType").value(hasItem(DEFAULT_SOURCE_TYPE.toString())))
            .andExpect(jsonPath("$.[*].dataDate").value(hasItem(DEFAULT_DATA_DATE.toString())))
            .andExpect(jsonPath("$.[*].changeDate").value(hasItem(DEFAULT_CHANGE_DATE.toString())))
            .andExpect(jsonPath("$.[*].changeUsername").value(hasItem(DEFAULT_CHANGE_USERNAME)))
            .andExpect(jsonPath("$.[*].dataSource").value(hasItem(DEFAULT_DATA_SOURCE)))
            .andExpect(jsonPath("$.[*].dataUser").value(hasItem(DEFAULT_DATA_USER)))
            .andExpect(jsonPath("$.[*].dataComments").value(hasItem(DEFAULT_DATA_COMMENTS)))
            .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 getAllInputDataWithEagerRelationshipsIsEnabled() throws Exception {
        when(inputDataServiceMock.findAllWithEagerRelationships(any())).thenReturn(new PageImpl(new ArrayList<>()));

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

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

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

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

    @Test
    @Transactional
    void getInputData() throws Exception {
        // Initialize the database
        insertedInputData = inputDataRepository.saveAndFlush(inputData);

        // Get the inputData
        restInputDataMockMvc
            .perform(get(ENTITY_API_URL_ID, inputData.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.id").value(inputData.getId().intValue()))
            .andExpect(jsonPath("$.sourceValue").value(sameNumber(DEFAULT_SOURCE_VALUE)))
            .andExpect(jsonPath("$.variableValue").value(sameNumber(DEFAULT_VARIABLE_VALUE)))
            .andExpect(jsonPath("$.imputedValue").value(sameNumber(DEFAULT_IMPUTED_VALUE)))
            .andExpect(jsonPath("$.sourceType").value(DEFAULT_SOURCE_TYPE.toString()))
            .andExpect(jsonPath("$.dataDate").value(DEFAULT_DATA_DATE.toString()))
            .andExpect(jsonPath("$.changeDate").value(DEFAULT_CHANGE_DATE.toString()))
            .andExpect(jsonPath("$.changeUsername").value(DEFAULT_CHANGE_USERNAME))
            .andExpect(jsonPath("$.dataSource").value(DEFAULT_DATA_SOURCE))
            .andExpect(jsonPath("$.dataUser").value(DEFAULT_DATA_USER))
            .andExpect(jsonPath("$.dataComments").value(DEFAULT_DATA_COMMENTS))
            .andExpect(jsonPath("$.creationDate").value(DEFAULT_CREATION_DATE.toString()))
            .andExpect(jsonPath("$.creationUsername").value(DEFAULT_CREATION_USERNAME))
            .andExpect(jsonPath("$.version").value(DEFAULT_VERSION));
    }

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

    @Test
    @Transactional
    void putExistingInputData() throws Exception {
        // Initialize the database
        insertedInputData = inputDataRepository.saveAndFlush(inputData);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the inputData
        InputData updatedInputData = inputDataRepository.findById(inputData.getId()).orElseThrow();
        // Disconnect from session so that the updates on updatedInputData are not directly saved in db
        em.detach(updatedInputData);
        updatedInputData
            .sourceValue(UPDATED_SOURCE_VALUE)
            .variableValue(UPDATED_VARIABLE_VALUE)
            .imputedValue(UPDATED_IMPUTED_VALUE)
            .sourceType(UPDATED_SOURCE_TYPE)
            .dataDate(UPDATED_DATA_DATE)
            .changeDate(UPDATED_CHANGE_DATE)
            .changeUsername(UPDATED_CHANGE_USERNAME)
            .dataSource(UPDATED_DATA_SOURCE)
            .dataUser(UPDATED_DATA_USER)
            .dataComments(UPDATED_DATA_COMMENTS)
            .creationDate(UPDATED_CREATION_DATE)
            .creationUsername(UPDATED_CREATION_USERNAME)
            .version(UPDATED_VERSION);
        InputDataDTO inputDataDTO = inputDataMapper.toDto(updatedInputData);

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

        // Validate the InputData in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertPersistedInputDataToMatchAllProperties(updatedInputData);
    }

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

        // Create the InputData
        InputDataDTO inputDataDTO = inputDataMapper.toDto(inputData);

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

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

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

        // Create the InputData
        InputDataDTO inputDataDTO = inputDataMapper.toDto(inputData);

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

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

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

        // Create the InputData
        InputDataDTO inputDataDTO = inputDataMapper.toDto(inputData);

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

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

    @Test
    @Transactional
    void partialUpdateInputDataWithPatch() throws Exception {
        // Initialize the database
        insertedInputData = inputDataRepository.saveAndFlush(inputData);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the inputData using partial update
        InputData partialUpdatedInputData = new InputData();
        partialUpdatedInputData.setId(inputData.getId());

        partialUpdatedInputData
            .imputedValue(UPDATED_IMPUTED_VALUE)
            .changeUsername(UPDATED_CHANGE_USERNAME)
            .dataSource(UPDATED_DATA_SOURCE)
            .dataUser(UPDATED_DATA_USER)
            .dataComments(UPDATED_DATA_COMMENTS)
            .creationUsername(UPDATED_CREATION_USERNAME);

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

        // Validate the InputData in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertInputDataUpdatableFieldsEquals(
            createUpdateProxyForBean(partialUpdatedInputData, inputData),
            getPersistedInputData(inputData)
        );
    }

    @Test
    @Transactional
    void fullUpdateInputDataWithPatch() throws Exception {
        // Initialize the database
        insertedInputData = inputDataRepository.saveAndFlush(inputData);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the inputData using partial update
        InputData partialUpdatedInputData = new InputData();
        partialUpdatedInputData.setId(inputData.getId());

        partialUpdatedInputData
            .sourceValue(UPDATED_SOURCE_VALUE)
            .variableValue(UPDATED_VARIABLE_VALUE)
            .imputedValue(UPDATED_IMPUTED_VALUE)
            .sourceType(UPDATED_SOURCE_TYPE)
            .dataDate(UPDATED_DATA_DATE)
            .changeDate(UPDATED_CHANGE_DATE)
            .changeUsername(UPDATED_CHANGE_USERNAME)
            .dataSource(UPDATED_DATA_SOURCE)
            .dataUser(UPDATED_DATA_USER)
            .dataComments(UPDATED_DATA_COMMENTS)
            .creationDate(UPDATED_CREATION_DATE)
            .creationUsername(UPDATED_CREATION_USERNAME)
            .version(UPDATED_VERSION);

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

        // Validate the InputData in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertInputDataUpdatableFieldsEquals(partialUpdatedInputData, getPersistedInputData(partialUpdatedInputData));
    }

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

        // Create the InputData
        InputDataDTO inputDataDTO = inputDataMapper.toDto(inputData);

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

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

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

        // Create the InputData
        InputDataDTO inputDataDTO = inputDataMapper.toDto(inputData);

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

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

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

        // Create the InputData
        InputDataDTO inputDataDTO = inputDataMapper.toDto(inputData);

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

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

    @Test
    @Transactional
    void deleteInputData() throws Exception {
        // Initialize the database
        insertedInputData = inputDataRepository.saveAndFlush(inputData);

        long databaseSizeBeforeDelete = getRepositoryCount();

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

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

    protected long getRepositoryCount() {
        return inputDataRepository.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 InputData getPersistedInputData(InputData inputData) {
        return inputDataRepository.findById(inputData.getId()).orElseThrow();
    }

    protected void assertPersistedInputDataToMatchAllProperties(InputData expectedInputData) {
        assertInputDataAllPropertiesEquals(expectedInputData, getPersistedInputData(expectedInputData));
    }

    protected void assertPersistedInputDataToMatchUpdatableProperties(InputData expectedInputData) {
        assertInputDataAllUpdatablePropertiesEquals(expectedInputData, getPersistedInputData(expectedInputData));
    }
}
