package com.oguerreiro.resilient.web.rest;

import static com.oguerreiro.resilient.domain.OutputDataAsserts.*;
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.OutputData;
import com.oguerreiro.resilient.repository.OutputDataRepository;
import com.oguerreiro.resilient.service.OutputDataService;
import com.oguerreiro.resilient.service.dto.OutputDataDTO;
import com.oguerreiro.resilient.service.mapper.OutputDataMapper;
import jakarta.persistence.EntityManager;
import java.math.BigDecimal;
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 OutputDataResource} REST controller.
 */
@IntegrationTest
@ExtendWith(MockitoExtension.class)
@AutoConfigureMockMvc
@WithMockUser
class OutputDataResourceIT {

    private static final BigDecimal DEFAULT_VALUE = new BigDecimal(1);
    private static final BigDecimal UPDATED_VALUE = new BigDecimal(2);

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

    private static final String ENTITY_API_URL = "/api/output-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 OutputDataRepository outputDataRepository;

    @Mock
    private OutputDataRepository outputDataRepositoryMock;

    @Autowired
    private OutputDataMapper outputDataMapper;

    @Mock
    private OutputDataService outputDataServiceMock;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restOutputDataMockMvc;

    private OutputData outputData;

    private OutputData insertedOutputData;

    /**
     * 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 OutputData createEntity(EntityManager em) {
        OutputData outputData = new OutputData().value(DEFAULT_VALUE).version(DEFAULT_VERSION);
        return outputData;
    }

    /**
     * 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 OutputData createUpdatedEntity(EntityManager em) {
        OutputData outputData = new OutputData().value(UPDATED_VALUE).version(UPDATED_VERSION);
        return outputData;
    }

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

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

    @Test
    @Transactional
    void createOutputData() throws Exception {
        long databaseSizeBeforeCreate = getRepositoryCount();
        // Create the OutputData
        OutputDataDTO outputDataDTO = outputDataMapper.toDto(outputData);
        var returnedOutputDataDTO = om.readValue(
            restOutputDataMockMvc
                .perform(
                    post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(outputDataDTO))
                )
                .andExpect(status().isCreated())
                .andReturn()
                .getResponse()
                .getContentAsString(),
            OutputDataDTO.class
        );

        // Validate the OutputData in the database
        assertIncrementedRepositoryCount(databaseSizeBeforeCreate);
        var returnedOutputData = outputDataMapper.toEntity(returnedOutputDataDTO);
        assertOutputDataUpdatableFieldsEquals(returnedOutputData, getPersistedOutputData(returnedOutputData));

        insertedOutputData = returnedOutputData;
    }

    @Test
    @Transactional
    void createOutputDataWithExistingId() throws Exception {
        // Create the OutputData with an existing ID
        outputData.setId(1L);
        OutputDataDTO outputDataDTO = outputDataMapper.toDto(outputData);

        long databaseSizeBeforeCreate = getRepositoryCount();

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

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

    @Test
    @Transactional
    void checkValueIsRequired() throws Exception {
        long databaseSizeBeforeTest = getRepositoryCount();
        // set the field null
        outputData.setValue(null);

        // Create the OutputData, which fails.
        OutputDataDTO outputDataDTO = outputDataMapper.toDto(outputData);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void getAllOutputData() throws Exception {
        // Initialize the database
        insertedOutputData = outputDataRepository.saveAndFlush(outputData);

        // Get all the outputDataList
        restOutputDataMockMvc
            .perform(get(ENTITY_API_URL + "?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(outputData.getId().intValue())))
            .andExpect(jsonPath("$.[*].value").value(hasItem(sameNumber(DEFAULT_VALUE))))
            .andExpect(jsonPath("$.[*].version").value(hasItem(DEFAULT_VERSION)));
    }

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

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

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

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

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

    @Test
    @Transactional
    void getOutputData() throws Exception {
        // Initialize the database
        insertedOutputData = outputDataRepository.saveAndFlush(outputData);

        // Get the outputData
        restOutputDataMockMvc
            .perform(get(ENTITY_API_URL_ID, outputData.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.id").value(outputData.getId().intValue()))
            .andExpect(jsonPath("$.value").value(sameNumber(DEFAULT_VALUE)))
            .andExpect(jsonPath("$.version").value(DEFAULT_VERSION));
    }

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

    @Test
    @Transactional
    void putExistingOutputData() throws Exception {
        // Initialize the database
        insertedOutputData = outputDataRepository.saveAndFlush(outputData);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the outputData
        OutputData updatedOutputData = outputDataRepository.findById(outputData.getId()).orElseThrow();
        // Disconnect from session so that the updates on updatedOutputData are not directly saved in db
        em.detach(updatedOutputData);
        updatedOutputData.value(UPDATED_VALUE).version(UPDATED_VERSION);
        OutputDataDTO outputDataDTO = outputDataMapper.toDto(updatedOutputData);

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

        // Validate the OutputData in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertPersistedOutputDataToMatchAllProperties(updatedOutputData);
    }

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

        // Create the OutputData
        OutputDataDTO outputDataDTO = outputDataMapper.toDto(outputData);

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

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

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

        // Create the OutputData
        OutputDataDTO outputDataDTO = outputDataMapper.toDto(outputData);

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

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

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

        // Create the OutputData
        OutputDataDTO outputDataDTO = outputDataMapper.toDto(outputData);

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

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

    @Test
    @Transactional
    void partialUpdateOutputDataWithPatch() throws Exception {
        // Initialize the database
        insertedOutputData = outputDataRepository.saveAndFlush(outputData);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the outputData using partial update
        OutputData partialUpdatedOutputData = new OutputData();
        partialUpdatedOutputData.setId(outputData.getId());

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

        // Validate the OutputData in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertOutputDataUpdatableFieldsEquals(
            createUpdateProxyForBean(partialUpdatedOutputData, outputData),
            getPersistedOutputData(outputData)
        );
    }

    @Test
    @Transactional
    void fullUpdateOutputDataWithPatch() throws Exception {
        // Initialize the database
        insertedOutputData = outputDataRepository.saveAndFlush(outputData);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the outputData using partial update
        OutputData partialUpdatedOutputData = new OutputData();
        partialUpdatedOutputData.setId(outputData.getId());

        partialUpdatedOutputData.value(UPDATED_VALUE).version(UPDATED_VERSION);

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

        // Validate the OutputData in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertOutputDataUpdatableFieldsEquals(partialUpdatedOutputData, getPersistedOutputData(partialUpdatedOutputData));
    }

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

        // Create the OutputData
        OutputDataDTO outputDataDTO = outputDataMapper.toDto(outputData);

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

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

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

        // Create the OutputData
        OutputDataDTO outputDataDTO = outputDataMapper.toDto(outputData);

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

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

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

        // Create the OutputData
        OutputDataDTO outputDataDTO = outputDataMapper.toDto(outputData);

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

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

    @Test
    @Transactional
    void deleteOutputData() throws Exception {
        // Initialize the database
        insertedOutputData = outputDataRepository.saveAndFlush(outputData);

        long databaseSizeBeforeDelete = getRepositoryCount();

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

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

    protected long getRepositoryCount() {
        return outputDataRepository.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 OutputData getPersistedOutputData(OutputData outputData) {
        return outputDataRepository.findById(outputData.getId()).orElseThrow();
    }

    protected void assertPersistedOutputDataToMatchAllProperties(OutputData expectedOutputData) {
        assertOutputDataAllPropertiesEquals(expectedOutputData, getPersistedOutputData(expectedOutputData));
    }

    protected void assertPersistedOutputDataToMatchUpdatableProperties(OutputData expectedOutputData) {
        assertOutputDataAllUpdatablePropertiesEquals(expectedOutputData, getPersistedOutputData(expectedOutputData));
    }
}
