package com.oguerreiro.resilient.web.rest;

import static com.oguerreiro.resilient.domain.VariableUnitsAsserts.*;
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.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.VariableUnits;
import com.oguerreiro.resilient.repository.VariableUnitsRepository;
import com.oguerreiro.resilient.service.VariableUnitsService;
import com.oguerreiro.resilient.service.dto.VariableUnitsDTO;
import com.oguerreiro.resilient.service.mapper.VariableUnitsMapper;
import jakarta.persistence.EntityManager;
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 VariableUnitsResource} REST controller.
 */
@IntegrationTest
@ExtendWith(MockitoExtension.class)
@AutoConfigureMockMvc
@WithMockUser
class VariableUnitsResourceIT {

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

    private static final String ENTITY_API_URL = "/api/variable-units";
    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 VariableUnitsRepository variableUnitsRepository;

    @Mock
    private VariableUnitsRepository variableUnitsRepositoryMock;

    @Autowired
    private VariableUnitsMapper variableUnitsMapper;

    @Mock
    private VariableUnitsService variableUnitsServiceMock;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restVariableUnitsMockMvc;

    private VariableUnits variableUnits;

    private VariableUnits insertedVariableUnits;

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

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

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

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

    @Test
    @Transactional
    void createVariableUnits() throws Exception {
        long databaseSizeBeforeCreate = getRepositoryCount();
        // Create the VariableUnits
        VariableUnitsDTO variableUnitsDTO = variableUnitsMapper.toDto(variableUnits);
        var returnedVariableUnitsDTO = om.readValue(
            restVariableUnitsMockMvc
                .perform(
                    post(ENTITY_API_URL)
                        .with(csrf())
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(om.writeValueAsBytes(variableUnitsDTO))
                )
                .andExpect(status().isCreated())
                .andReturn()
                .getResponse()
                .getContentAsString(),
            VariableUnitsDTO.class
        );

        // Validate the VariableUnits in the database
        assertIncrementedRepositoryCount(databaseSizeBeforeCreate);
        var returnedVariableUnits = variableUnitsMapper.toEntity(returnedVariableUnitsDTO);
        assertVariableUnitsUpdatableFieldsEquals(returnedVariableUnits, getPersistedVariableUnits(returnedVariableUnits));

        insertedVariableUnits = returnedVariableUnits;
    }

    @Test
    @Transactional
    void createVariableUnitsWithExistingId() throws Exception {
        // Create the VariableUnits with an existing ID
        variableUnits.setId(1L);
        VariableUnitsDTO variableUnitsDTO = variableUnitsMapper.toDto(variableUnits);

        long databaseSizeBeforeCreate = getRepositoryCount();

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

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

    @Test
    @Transactional
    void getAllVariableUnits() throws Exception {
        // Initialize the database
        insertedVariableUnits = variableUnitsRepository.saveAndFlush(variableUnits);

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

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

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

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

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

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

    @Test
    @Transactional
    void getVariableUnits() throws Exception {
        // Initialize the database
        insertedVariableUnits = variableUnitsRepository.saveAndFlush(variableUnits);

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

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

    @Test
    @Transactional
    void putExistingVariableUnits() throws Exception {
        // Initialize the database
        insertedVariableUnits = variableUnitsRepository.saveAndFlush(variableUnits);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the variableUnits
        VariableUnits updatedVariableUnits = variableUnitsRepository.findById(variableUnits.getId()).orElseThrow();
        // Disconnect from session so that the updates on updatedVariableUnits are not directly saved in db
        em.detach(updatedVariableUnits);
        updatedVariableUnits.version(UPDATED_VERSION);
        VariableUnitsDTO variableUnitsDTO = variableUnitsMapper.toDto(updatedVariableUnits);

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

        // Validate the VariableUnits in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertPersistedVariableUnitsToMatchAllProperties(updatedVariableUnits);
    }

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

        // Create the VariableUnits
        VariableUnitsDTO variableUnitsDTO = variableUnitsMapper.toDto(variableUnits);

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

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

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

        // Create the VariableUnits
        VariableUnitsDTO variableUnitsDTO = variableUnitsMapper.toDto(variableUnits);

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

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

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

        // Create the VariableUnits
        VariableUnitsDTO variableUnitsDTO = variableUnitsMapper.toDto(variableUnits);

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

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

    @Test
    @Transactional
    void partialUpdateVariableUnitsWithPatch() throws Exception {
        // Initialize the database
        insertedVariableUnits = variableUnitsRepository.saveAndFlush(variableUnits);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the variableUnits using partial update
        VariableUnits partialUpdatedVariableUnits = new VariableUnits();
        partialUpdatedVariableUnits.setId(variableUnits.getId());

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

        // Validate the VariableUnits in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertVariableUnitsUpdatableFieldsEquals(
            createUpdateProxyForBean(partialUpdatedVariableUnits, variableUnits),
            getPersistedVariableUnits(variableUnits)
        );
    }

    @Test
    @Transactional
    void fullUpdateVariableUnitsWithPatch() throws Exception {
        // Initialize the database
        insertedVariableUnits = variableUnitsRepository.saveAndFlush(variableUnits);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the variableUnits using partial update
        VariableUnits partialUpdatedVariableUnits = new VariableUnits();
        partialUpdatedVariableUnits.setId(variableUnits.getId());

        partialUpdatedVariableUnits.version(UPDATED_VERSION);

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

        // Validate the VariableUnits in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertVariableUnitsUpdatableFieldsEquals(partialUpdatedVariableUnits, getPersistedVariableUnits(partialUpdatedVariableUnits));
    }

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

        // Create the VariableUnits
        VariableUnitsDTO variableUnitsDTO = variableUnitsMapper.toDto(variableUnits);

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

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

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

        // Create the VariableUnits
        VariableUnitsDTO variableUnitsDTO = variableUnitsMapper.toDto(variableUnits);

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

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

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

        // Create the VariableUnits
        VariableUnitsDTO variableUnitsDTO = variableUnitsMapper.toDto(variableUnits);

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

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

    @Test
    @Transactional
    void deleteVariableUnits() throws Exception {
        // Initialize the database
        insertedVariableUnits = variableUnitsRepository.saveAndFlush(variableUnits);

        long databaseSizeBeforeDelete = getRepositoryCount();

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

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

    protected long getRepositoryCount() {
        return variableUnitsRepository.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 VariableUnits getPersistedVariableUnits(VariableUnits variableUnits) {
        return variableUnitsRepository.findById(variableUnits.getId()).orElseThrow();
    }

    protected void assertPersistedVariableUnitsToMatchAllProperties(VariableUnits expectedVariableUnits) {
        assertVariableUnitsAllPropertiesEquals(expectedVariableUnits, getPersistedVariableUnits(expectedVariableUnits));
    }

    protected void assertPersistedVariableUnitsToMatchUpdatableProperties(VariableUnits expectedVariableUnits) {
        assertVariableUnitsAllUpdatablePropertiesEquals(expectedVariableUnits, getPersistedVariableUnits(expectedVariableUnits));
    }
}
