package com.oguerreiro.resilient.web.rest;

import static com.oguerreiro.resilient.domain.VariableCategoryAsserts.*;
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.VariableCategory;
import com.oguerreiro.resilient.repository.VariableCategoryRepository;
import com.oguerreiro.resilient.service.VariableCategoryService;
import com.oguerreiro.resilient.service.dto.VariableCategoryDTO;
import com.oguerreiro.resilient.service.mapper.VariableCategoryMapper;
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 VariableCategoryResource} REST controller.
 */
@IntegrationTest
@ExtendWith(MockitoExtension.class)
@AutoConfigureMockMvc
@WithMockUser
class VariableCategoryResourceIT {

    private static final String DEFAULT_CODE = "30540";
    private static final String UPDATED_CODE = "0330";

    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 Integer DEFAULT_VERSION = 1;
    private static final Integer UPDATED_VERSION = 2;

    private static final String ENTITY_API_URL = "/api/variable-categories";
    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 VariableCategoryRepository variableCategoryRepository;

    @Mock
    private VariableCategoryRepository variableCategoryRepositoryMock;

    @Autowired
    private VariableCategoryMapper variableCategoryMapper;

    @Mock
    private VariableCategoryService variableCategoryServiceMock;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restVariableCategoryMockMvc;

    private VariableCategory variableCategory;

    private VariableCategory insertedVariableCategory;

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

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

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

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

    @Test
    @Transactional
    void createVariableCategory() throws Exception {
        long databaseSizeBeforeCreate = getRepositoryCount();
        // Create the VariableCategory
        VariableCategoryDTO variableCategoryDTO = variableCategoryMapper.toDto(variableCategory);
        var returnedVariableCategoryDTO = om.readValue(
            restVariableCategoryMockMvc
                .perform(
                    post(ENTITY_API_URL)
                        .with(csrf())
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(om.writeValueAsBytes(variableCategoryDTO))
                )
                .andExpect(status().isCreated())
                .andReturn()
                .getResponse()
                .getContentAsString(),
            VariableCategoryDTO.class
        );

        // Validate the VariableCategory in the database
        assertIncrementedRepositoryCount(databaseSizeBeforeCreate);
        var returnedVariableCategory = variableCategoryMapper.toEntity(returnedVariableCategoryDTO);
        assertVariableCategoryUpdatableFieldsEquals(returnedVariableCategory, getPersistedVariableCategory(returnedVariableCategory));

        insertedVariableCategory = returnedVariableCategory;
    }

    @Test
    @Transactional
    void createVariableCategoryWithExistingId() throws Exception {
        // Create the VariableCategory with an existing ID
        variableCategory.setId(1L);
        VariableCategoryDTO variableCategoryDTO = variableCategoryMapper.toDto(variableCategory);

        long databaseSizeBeforeCreate = getRepositoryCount();

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

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

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

        // Create the VariableCategory, which fails.
        VariableCategoryDTO variableCategoryDTO = variableCategoryMapper.toDto(variableCategory);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

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

        // Create the VariableCategory, which fails.
        VariableCategoryDTO variableCategoryDTO = variableCategoryMapper.toDto(variableCategory);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

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

        // Create the VariableCategory, which fails.
        VariableCategoryDTO variableCategoryDTO = variableCategoryMapper.toDto(variableCategory);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void getAllVariableCategories() throws Exception {
        // Initialize the database
        insertedVariableCategory = variableCategoryRepository.saveAndFlush(variableCategory);

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

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

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

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

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

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

    @Test
    @Transactional
    void getVariableCategory() throws Exception {
        // Initialize the database
        insertedVariableCategory = variableCategoryRepository.saveAndFlush(variableCategory);

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

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

    @Test
    @Transactional
    void putExistingVariableCategory() throws Exception {
        // Initialize the database
        insertedVariableCategory = variableCategoryRepository.saveAndFlush(variableCategory);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the variableCategory
        VariableCategory updatedVariableCategory = variableCategoryRepository.findById(variableCategory.getId()).orElseThrow();
        // Disconnect from session so that the updates on updatedVariableCategory are not directly saved in db
        em.detach(updatedVariableCategory);
        updatedVariableCategory.code(UPDATED_CODE).name(UPDATED_NAME).description(UPDATED_DESCRIPTION).version(UPDATED_VERSION);
        VariableCategoryDTO variableCategoryDTO = variableCategoryMapper.toDto(updatedVariableCategory);

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

        // Validate the VariableCategory in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertPersistedVariableCategoryToMatchAllProperties(updatedVariableCategory);
    }

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

        // Create the VariableCategory
        VariableCategoryDTO variableCategoryDTO = variableCategoryMapper.toDto(variableCategory);

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

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

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

        // Create the VariableCategory
        VariableCategoryDTO variableCategoryDTO = variableCategoryMapper.toDto(variableCategory);

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

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

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

        // Create the VariableCategory
        VariableCategoryDTO variableCategoryDTO = variableCategoryMapper.toDto(variableCategory);

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

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

    @Test
    @Transactional
    void partialUpdateVariableCategoryWithPatch() throws Exception {
        // Initialize the database
        insertedVariableCategory = variableCategoryRepository.saveAndFlush(variableCategory);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the variableCategory using partial update
        VariableCategory partialUpdatedVariableCategory = new VariableCategory();
        partialUpdatedVariableCategory.setId(variableCategory.getId());

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

        // Validate the VariableCategory in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertVariableCategoryUpdatableFieldsEquals(
            createUpdateProxyForBean(partialUpdatedVariableCategory, variableCategory),
            getPersistedVariableCategory(variableCategory)
        );
    }

    @Test
    @Transactional
    void fullUpdateVariableCategoryWithPatch() throws Exception {
        // Initialize the database
        insertedVariableCategory = variableCategoryRepository.saveAndFlush(variableCategory);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the variableCategory using partial update
        VariableCategory partialUpdatedVariableCategory = new VariableCategory();
        partialUpdatedVariableCategory.setId(variableCategory.getId());

        partialUpdatedVariableCategory.code(UPDATED_CODE).name(UPDATED_NAME).description(UPDATED_DESCRIPTION).version(UPDATED_VERSION);

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

        // Validate the VariableCategory in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertVariableCategoryUpdatableFieldsEquals(
            partialUpdatedVariableCategory,
            getPersistedVariableCategory(partialUpdatedVariableCategory)
        );
    }

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

        // Create the VariableCategory
        VariableCategoryDTO variableCategoryDTO = variableCategoryMapper.toDto(variableCategory);

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

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

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

        // Create the VariableCategory
        VariableCategoryDTO variableCategoryDTO = variableCategoryMapper.toDto(variableCategory);

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

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

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

        // Create the VariableCategory
        VariableCategoryDTO variableCategoryDTO = variableCategoryMapper.toDto(variableCategory);

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

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

    @Test
    @Transactional
    void deleteVariableCategory() throws Exception {
        // Initialize the database
        insertedVariableCategory = variableCategoryRepository.saveAndFlush(variableCategory);

        long databaseSizeBeforeDelete = getRepositoryCount();

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

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

    protected long getRepositoryCount() {
        return variableCategoryRepository.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 VariableCategory getPersistedVariableCategory(VariableCategory variableCategory) {
        return variableCategoryRepository.findById(variableCategory.getId()).orElseThrow();
    }

    protected void assertPersistedVariableCategoryToMatchAllProperties(VariableCategory expectedVariableCategory) {
        assertVariableCategoryAllPropertiesEquals(expectedVariableCategory, getPersistedVariableCategory(expectedVariableCategory));
    }

    protected void assertPersistedVariableCategoryToMatchUpdatableProperties(VariableCategory expectedVariableCategory) {
        assertVariableCategoryAllUpdatablePropertiesEquals(
            expectedVariableCategory,
            getPersistedVariableCategory(expectedVariableCategory)
        );
    }
}
