package com.oguerreiro.resilient.web.rest;

import static com.oguerreiro.resilient.domain.VariableClassAsserts.*;
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.VariableClass;
import com.oguerreiro.resilient.repository.VariableClassRepository;
import com.oguerreiro.resilient.service.VariableClassService;
import com.oguerreiro.resilient.service.dto.VariableClassDTO;
import com.oguerreiro.resilient.service.mapper.VariableClassMapper;
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 VariableClassResource} REST controller.
 */
@IntegrationTest
@ExtendWith(MockitoExtension.class)
@AutoConfigureMockMvc
@WithMockUser
class VariableClassResourceIT {

    private static final String DEFAULT_CODE = "AAAAAAAAAA";
    private static final String UPDATED_CODE = "BBBBBBBBBB";

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

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

    private static final String ENTITY_API_URL = "/api/variable-classes";
    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 VariableClassRepository variableClassRepository;

    @Mock
    private VariableClassRepository variableClassRepositoryMock;

    @Autowired
    private VariableClassMapper variableClassMapper;

    @Mock
    private VariableClassService variableClassServiceMock;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restVariableClassMockMvc;

    private VariableClass variableClass;

    private VariableClass insertedVariableClass;

    /**
     * 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 VariableClass createEntity(EntityManager em) {
        VariableClass variableClass = new VariableClass().code(DEFAULT_CODE).name(DEFAULT_NAME).version(DEFAULT_VERSION);
        return variableClass;
    }

    /**
     * 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 VariableClass createUpdatedEntity(EntityManager em) {
        VariableClass variableClass = new VariableClass().code(UPDATED_CODE).name(UPDATED_NAME).version(UPDATED_VERSION);
        return variableClass;
    }

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

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

    @Test
    @Transactional
    void createVariableClass() throws Exception {
        long databaseSizeBeforeCreate = getRepositoryCount();
        // Create the VariableClass
        VariableClassDTO variableClassDTO = variableClassMapper.toDto(variableClass);
        var returnedVariableClassDTO = om.readValue(
            restVariableClassMockMvc
                .perform(
                    post(ENTITY_API_URL)
                        .with(csrf())
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(om.writeValueAsBytes(variableClassDTO))
                )
                .andExpect(status().isCreated())
                .andReturn()
                .getResponse()
                .getContentAsString(),
            VariableClassDTO.class
        );

        // Validate the VariableClass in the database
        assertIncrementedRepositoryCount(databaseSizeBeforeCreate);
        var returnedVariableClass = variableClassMapper.toEntity(returnedVariableClassDTO);
        assertVariableClassUpdatableFieldsEquals(returnedVariableClass, getPersistedVariableClass(returnedVariableClass));

        insertedVariableClass = returnedVariableClass;
    }

    @Test
    @Transactional
    void createVariableClassWithExistingId() throws Exception {
        // Create the VariableClass with an existing ID
        variableClass.setId(1L);
        VariableClassDTO variableClassDTO = variableClassMapper.toDto(variableClass);

        long databaseSizeBeforeCreate = getRepositoryCount();

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

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

    @Test
    @Transactional
    void checkCodeIsRequired() throws Exception {
        long databaseSizeBeforeTest = getRepositoryCount();
        // set the field null
        variableClass.setCode(null);

        // Create the VariableClass, which fails.
        VariableClassDTO variableClassDTO = variableClassMapper.toDto(variableClass);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

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

        // Create the VariableClass, which fails.
        VariableClassDTO variableClassDTO = variableClassMapper.toDto(variableClass);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void getAllVariableClasses() throws Exception {
        // Initialize the database
        insertedVariableClass = variableClassRepository.saveAndFlush(variableClass);

        // Get all the variableClassList
        restVariableClassMockMvc
            .perform(get(ENTITY_API_URL + "?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(variableClass.getId().intValue())))
            .andExpect(jsonPath("$.[*].code").value(hasItem(DEFAULT_CODE)))
            .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME)))
            .andExpect(jsonPath("$.[*].version").value(hasItem(DEFAULT_VERSION)));
    }

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

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

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

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

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

    @Test
    @Transactional
    void getVariableClass() throws Exception {
        // Initialize the database
        insertedVariableClass = variableClassRepository.saveAndFlush(variableClass);

        // Get the variableClass
        restVariableClassMockMvc
            .perform(get(ENTITY_API_URL_ID, variableClass.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.id").value(variableClass.getId().intValue()))
            .andExpect(jsonPath("$.code").value(DEFAULT_CODE))
            .andExpect(jsonPath("$.name").value(DEFAULT_NAME))
            .andExpect(jsonPath("$.version").value(DEFAULT_VERSION));
    }

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

    @Test
    @Transactional
    void putExistingVariableClass() throws Exception {
        // Initialize the database
        insertedVariableClass = variableClassRepository.saveAndFlush(variableClass);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the variableClass
        VariableClass updatedVariableClass = variableClassRepository.findById(variableClass.getId()).orElseThrow();
        // Disconnect from session so that the updates on updatedVariableClass are not directly saved in db
        em.detach(updatedVariableClass);
        updatedVariableClass.code(UPDATED_CODE).name(UPDATED_NAME).version(UPDATED_VERSION);
        VariableClassDTO variableClassDTO = variableClassMapper.toDto(updatedVariableClass);

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

        // Validate the VariableClass in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertPersistedVariableClassToMatchAllProperties(updatedVariableClass);
    }

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

        // Create the VariableClass
        VariableClassDTO variableClassDTO = variableClassMapper.toDto(variableClass);

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

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

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

        // Create the VariableClass
        VariableClassDTO variableClassDTO = variableClassMapper.toDto(variableClass);

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

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

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

        // Create the VariableClass
        VariableClassDTO variableClassDTO = variableClassMapper.toDto(variableClass);

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

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

    @Test
    @Transactional
    void partialUpdateVariableClassWithPatch() throws Exception {
        // Initialize the database
        insertedVariableClass = variableClassRepository.saveAndFlush(variableClass);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the variableClass using partial update
        VariableClass partialUpdatedVariableClass = new VariableClass();
        partialUpdatedVariableClass.setId(variableClass.getId());

        partialUpdatedVariableClass.code(UPDATED_CODE).name(UPDATED_NAME);

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

        // Validate the VariableClass in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertVariableClassUpdatableFieldsEquals(
            createUpdateProxyForBean(partialUpdatedVariableClass, variableClass),
            getPersistedVariableClass(variableClass)
        );
    }

    @Test
    @Transactional
    void fullUpdateVariableClassWithPatch() throws Exception {
        // Initialize the database
        insertedVariableClass = variableClassRepository.saveAndFlush(variableClass);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the variableClass using partial update
        VariableClass partialUpdatedVariableClass = new VariableClass();
        partialUpdatedVariableClass.setId(variableClass.getId());

        partialUpdatedVariableClass.code(UPDATED_CODE).name(UPDATED_NAME).version(UPDATED_VERSION);

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

        // Validate the VariableClass in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertVariableClassUpdatableFieldsEquals(partialUpdatedVariableClass, getPersistedVariableClass(partialUpdatedVariableClass));
    }

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

        // Create the VariableClass
        VariableClassDTO variableClassDTO = variableClassMapper.toDto(variableClass);

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

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

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

        // Create the VariableClass
        VariableClassDTO variableClassDTO = variableClassMapper.toDto(variableClass);

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

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

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

        // Create the VariableClass
        VariableClassDTO variableClassDTO = variableClassMapper.toDto(variableClass);

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

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

    @Test
    @Transactional
    void deleteVariableClass() throws Exception {
        // Initialize the database
        insertedVariableClass = variableClassRepository.saveAndFlush(variableClass);

        long databaseSizeBeforeDelete = getRepositoryCount();

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

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

    protected long getRepositoryCount() {
        return variableClassRepository.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 VariableClass getPersistedVariableClass(VariableClass variableClass) {
        return variableClassRepository.findById(variableClass.getId()).orElseThrow();
    }

    protected void assertPersistedVariableClassToMatchAllProperties(VariableClass expectedVariableClass) {
        assertVariableClassAllPropertiesEquals(expectedVariableClass, getPersistedVariableClass(expectedVariableClass));
    }

    protected void assertPersistedVariableClassToMatchUpdatableProperties(VariableClass expectedVariableClass) {
        assertVariableClassAllUpdatablePropertiesEquals(expectedVariableClass, getPersistedVariableClass(expectedVariableClass));
    }
}
