package com.oguerreiro.resilient.web.rest;

import static com.oguerreiro.resilient.domain.UnitConverterAsserts.*;
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.UnitConverter;
import com.oguerreiro.resilient.repository.UnitConverterRepository;
import com.oguerreiro.resilient.service.UnitConverterService;
import com.oguerreiro.resilient.service.dto.UnitConverterDTO;
import com.oguerreiro.resilient.service.mapper.UnitConverterMapper;
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 UnitConverterResource} REST controller.
 */
@IntegrationTest
@ExtendWith(MockitoExtension.class)
@AutoConfigureMockMvc
@WithMockUser
class UnitConverterResourceIT {

    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 String DEFAULT_CONVERTION_FORMULA = "AAAAAAAAAA";
    private static final String UPDATED_CONVERTION_FORMULA = "BBBBBBBBBB";

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

    private static final String ENTITY_API_URL = "/api/unit-converters";
    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 UnitConverterRepository unitConverterRepository;

    @Mock
    private UnitConverterRepository unitConverterRepositoryMock;

    @Autowired
    private UnitConverterMapper unitConverterMapper;

    @Mock
    private UnitConverterService unitConverterServiceMock;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restUnitConverterMockMvc;

    private UnitConverter unitConverter;

    private UnitConverter insertedUnitConverter;

    /**
     * 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 UnitConverter createEntity(EntityManager em) {
        UnitConverter unitConverter = new UnitConverter()
            .name(DEFAULT_NAME)
            .description(DEFAULT_DESCRIPTION)
            .convertionFormula(DEFAULT_CONVERTION_FORMULA)
            .version(DEFAULT_VERSION);
        return unitConverter;
    }

    /**
     * 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 UnitConverter createUpdatedEntity(EntityManager em) {
        UnitConverter unitConverter = new UnitConverter()
            .name(UPDATED_NAME)
            .description(UPDATED_DESCRIPTION)
            .convertionFormula(UPDATED_CONVERTION_FORMULA)
            .version(UPDATED_VERSION);
        return unitConverter;
    }

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

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

    @Test
    @Transactional
    void createUnitConverter() throws Exception {
        long databaseSizeBeforeCreate = getRepositoryCount();
        // Create the UnitConverter
        UnitConverterDTO unitConverterDTO = unitConverterMapper.toDto(unitConverter);
        var returnedUnitConverterDTO = om.readValue(
            restUnitConverterMockMvc
                .perform(
                    post(ENTITY_API_URL)
                        .with(csrf())
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(om.writeValueAsBytes(unitConverterDTO))
                )
                .andExpect(status().isCreated())
                .andReturn()
                .getResponse()
                .getContentAsString(),
            UnitConverterDTO.class
        );

        // Validate the UnitConverter in the database
        assertIncrementedRepositoryCount(databaseSizeBeforeCreate);
        var returnedUnitConverter = unitConverterMapper.toEntity(returnedUnitConverterDTO);
        assertUnitConverterUpdatableFieldsEquals(returnedUnitConverter, getPersistedUnitConverter(returnedUnitConverter));

        insertedUnitConverter = returnedUnitConverter;
    }

    @Test
    @Transactional
    void createUnitConverterWithExistingId() throws Exception {
        // Create the UnitConverter with an existing ID
        unitConverter.setId(1L);
        UnitConverterDTO unitConverterDTO = unitConverterMapper.toDto(unitConverter);

        long databaseSizeBeforeCreate = getRepositoryCount();

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

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

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

        // Create the UnitConverter, which fails.
        UnitConverterDTO unitConverterDTO = unitConverterMapper.toDto(unitConverter);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void checkDescriptionIsRequired() throws Exception {
        long databaseSizeBeforeTest = getRepositoryCount();
        // set the field null
        unitConverter.setDescription(null);

        // Create the UnitConverter, which fails.
        UnitConverterDTO unitConverterDTO = unitConverterMapper.toDto(unitConverter);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void checkConvertionFormulaIsRequired() throws Exception {
        long databaseSizeBeforeTest = getRepositoryCount();
        // set the field null
        unitConverter.setConvertionFormula(null);

        // Create the UnitConverter, which fails.
        UnitConverterDTO unitConverterDTO = unitConverterMapper.toDto(unitConverter);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void getAllUnitConverters() throws Exception {
        // Initialize the database
        insertedUnitConverter = unitConverterRepository.saveAndFlush(unitConverter);

        // Get all the unitConverterList
        restUnitConverterMockMvc
            .perform(get(ENTITY_API_URL + "?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(unitConverter.getId().intValue())))
            .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME)))
            .andExpect(jsonPath("$.[*].description").value(hasItem(DEFAULT_DESCRIPTION)))
            .andExpect(jsonPath("$.[*].convertionFormula").value(hasItem(DEFAULT_CONVERTION_FORMULA)))
            .andExpect(jsonPath("$.[*].version").value(hasItem(DEFAULT_VERSION)));
    }

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

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

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

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

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

    @Test
    @Transactional
    void getUnitConverter() throws Exception {
        // Initialize the database
        insertedUnitConverter = unitConverterRepository.saveAndFlush(unitConverter);

        // Get the unitConverter
        restUnitConverterMockMvc
            .perform(get(ENTITY_API_URL_ID, unitConverter.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.id").value(unitConverter.getId().intValue()))
            .andExpect(jsonPath("$.name").value(DEFAULT_NAME))
            .andExpect(jsonPath("$.description").value(DEFAULT_DESCRIPTION))
            .andExpect(jsonPath("$.convertionFormula").value(DEFAULT_CONVERTION_FORMULA))
            .andExpect(jsonPath("$.version").value(DEFAULT_VERSION));
    }

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

    @Test
    @Transactional
    void putExistingUnitConverter() throws Exception {
        // Initialize the database
        insertedUnitConverter = unitConverterRepository.saveAndFlush(unitConverter);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the unitConverter
        UnitConverter updatedUnitConverter = unitConverterRepository.findById(unitConverter.getId()).orElseThrow();
        // Disconnect from session so that the updates on updatedUnitConverter are not directly saved in db
        em.detach(updatedUnitConverter);
        updatedUnitConverter
            .name(UPDATED_NAME)
            .description(UPDATED_DESCRIPTION)
            .convertionFormula(UPDATED_CONVERTION_FORMULA)
            .version(UPDATED_VERSION);
        UnitConverterDTO unitConverterDTO = unitConverterMapper.toDto(updatedUnitConverter);

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

        // Validate the UnitConverter in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertPersistedUnitConverterToMatchAllProperties(updatedUnitConverter);
    }

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

        // Create the UnitConverter
        UnitConverterDTO unitConverterDTO = unitConverterMapper.toDto(unitConverter);

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

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

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

        // Create the UnitConverter
        UnitConverterDTO unitConverterDTO = unitConverterMapper.toDto(unitConverter);

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

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

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

        // Create the UnitConverter
        UnitConverterDTO unitConverterDTO = unitConverterMapper.toDto(unitConverter);

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

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

    @Test
    @Transactional
    void partialUpdateUnitConverterWithPatch() throws Exception {
        // Initialize the database
        insertedUnitConverter = unitConverterRepository.saveAndFlush(unitConverter);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the unitConverter using partial update
        UnitConverter partialUpdatedUnitConverter = new UnitConverter();
        partialUpdatedUnitConverter.setId(unitConverter.getId());

        partialUpdatedUnitConverter.name(UPDATED_NAME).description(UPDATED_DESCRIPTION).version(UPDATED_VERSION);

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

        // Validate the UnitConverter in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertUnitConverterUpdatableFieldsEquals(
            createUpdateProxyForBean(partialUpdatedUnitConverter, unitConverter),
            getPersistedUnitConverter(unitConverter)
        );
    }

    @Test
    @Transactional
    void fullUpdateUnitConverterWithPatch() throws Exception {
        // Initialize the database
        insertedUnitConverter = unitConverterRepository.saveAndFlush(unitConverter);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the unitConverter using partial update
        UnitConverter partialUpdatedUnitConverter = new UnitConverter();
        partialUpdatedUnitConverter.setId(unitConverter.getId());

        partialUpdatedUnitConverter
            .name(UPDATED_NAME)
            .description(UPDATED_DESCRIPTION)
            .convertionFormula(UPDATED_CONVERTION_FORMULA)
            .version(UPDATED_VERSION);

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

        // Validate the UnitConverter in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertUnitConverterUpdatableFieldsEquals(partialUpdatedUnitConverter, getPersistedUnitConverter(partialUpdatedUnitConverter));
    }

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

        // Create the UnitConverter
        UnitConverterDTO unitConverterDTO = unitConverterMapper.toDto(unitConverter);

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

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

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

        // Create the UnitConverter
        UnitConverterDTO unitConverterDTO = unitConverterMapper.toDto(unitConverter);

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

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

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

        // Create the UnitConverter
        UnitConverterDTO unitConverterDTO = unitConverterMapper.toDto(unitConverter);

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

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

    @Test
    @Transactional
    void deleteUnitConverter() throws Exception {
        // Initialize the database
        insertedUnitConverter = unitConverterRepository.saveAndFlush(unitConverter);

        long databaseSizeBeforeDelete = getRepositoryCount();

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

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

    protected long getRepositoryCount() {
        return unitConverterRepository.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 UnitConverter getPersistedUnitConverter(UnitConverter unitConverter) {
        return unitConverterRepository.findById(unitConverter.getId()).orElseThrow();
    }

    protected void assertPersistedUnitConverterToMatchAllProperties(UnitConverter expectedUnitConverter) {
        assertUnitConverterAllPropertiesEquals(expectedUnitConverter, getPersistedUnitConverter(expectedUnitConverter));
    }

    protected void assertPersistedUnitConverterToMatchUpdatableProperties(UnitConverter expectedUnitConverter) {
        assertUnitConverterAllUpdatablePropertiesEquals(expectedUnitConverter, getPersistedUnitConverter(expectedUnitConverter));
    }
}
