package com.oguerreiro.resilient.web.rest;

import static com.oguerreiro.resilient.domain.VariableScopeAsserts.*;
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.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.VariableScope;
import com.oguerreiro.resilient.repository.VariableScopeRepository;
import com.oguerreiro.resilient.service.dto.VariableScopeDTO;
import com.oguerreiro.resilient.service.mapper.VariableScopeMapper;
import jakarta.persistence.EntityManager;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
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 VariableScopeResource} REST controller.
 */
@IntegrationTest
@AutoConfigureMockMvc
@WithMockUser
class VariableScopeResourceIT {

    private static final String DEFAULT_CODE = "98";
    private static final String UPDATED_CODE = "33";

    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-scopes";
    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 VariableScopeRepository variableScopeRepository;

    @Autowired
    private VariableScopeMapper variableScopeMapper;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restVariableScopeMockMvc;

    private VariableScope variableScope;

    private VariableScope insertedVariableScope;

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

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

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

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

    @Test
    @Transactional
    void createVariableScope() throws Exception {
        long databaseSizeBeforeCreate = getRepositoryCount();
        // Create the VariableScope
        VariableScopeDTO variableScopeDTO = variableScopeMapper.toDto(variableScope);
        var returnedVariableScopeDTO = om.readValue(
            restVariableScopeMockMvc
                .perform(
                    post(ENTITY_API_URL)
                        .with(csrf())
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(om.writeValueAsBytes(variableScopeDTO))
                )
                .andExpect(status().isCreated())
                .andReturn()
                .getResponse()
                .getContentAsString(),
            VariableScopeDTO.class
        );

        // Validate the VariableScope in the database
        assertIncrementedRepositoryCount(databaseSizeBeforeCreate);
        var returnedVariableScope = variableScopeMapper.toEntity(returnedVariableScopeDTO);
        assertVariableScopeUpdatableFieldsEquals(returnedVariableScope, getPersistedVariableScope(returnedVariableScope));

        insertedVariableScope = returnedVariableScope;
    }

    @Test
    @Transactional
    void createVariableScopeWithExistingId() throws Exception {
        // Create the VariableScope with an existing ID
        variableScope.setId(1L);
        VariableScopeDTO variableScopeDTO = variableScopeMapper.toDto(variableScope);

        long databaseSizeBeforeCreate = getRepositoryCount();

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

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

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

        // Create the VariableScope, which fails.
        VariableScopeDTO variableScopeDTO = variableScopeMapper.toDto(variableScope);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

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

        // Create the VariableScope, which fails.
        VariableScopeDTO variableScopeDTO = variableScopeMapper.toDto(variableScope);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

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

        // Create the VariableScope, which fails.
        VariableScopeDTO variableScopeDTO = variableScopeMapper.toDto(variableScope);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void getAllVariableScopes() throws Exception {
        // Initialize the database
        insertedVariableScope = variableScopeRepository.saveAndFlush(variableScope);

        // Get all the variableScopeList
        restVariableScopeMockMvc
            .perform(get(ENTITY_API_URL + "?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(variableScope.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)));
    }

    @Test
    @Transactional
    void getVariableScope() throws Exception {
        // Initialize the database
        insertedVariableScope = variableScopeRepository.saveAndFlush(variableScope);

        // Get the variableScope
        restVariableScopeMockMvc
            .perform(get(ENTITY_API_URL_ID, variableScope.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.id").value(variableScope.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 getNonExistingVariableScope() throws Exception {
        // Get the variableScope
        restVariableScopeMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound());
    }

    @Test
    @Transactional
    void putExistingVariableScope() throws Exception {
        // Initialize the database
        insertedVariableScope = variableScopeRepository.saveAndFlush(variableScope);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the variableScope
        VariableScope updatedVariableScope = variableScopeRepository.findById(variableScope.getId()).orElseThrow();
        // Disconnect from session so that the updates on updatedVariableScope are not directly saved in db
        em.detach(updatedVariableScope);
        updatedVariableScope.code(UPDATED_CODE).name(UPDATED_NAME).description(UPDATED_DESCRIPTION).version(UPDATED_VERSION);
        VariableScopeDTO variableScopeDTO = variableScopeMapper.toDto(updatedVariableScope);

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

        // Validate the VariableScope in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertPersistedVariableScopeToMatchAllProperties(updatedVariableScope);
    }

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

        // Create the VariableScope
        VariableScopeDTO variableScopeDTO = variableScopeMapper.toDto(variableScope);

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

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

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

        // Create the VariableScope
        VariableScopeDTO variableScopeDTO = variableScopeMapper.toDto(variableScope);

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

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

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

        // Create the VariableScope
        VariableScopeDTO variableScopeDTO = variableScopeMapper.toDto(variableScope);

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

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

    @Test
    @Transactional
    void partialUpdateVariableScopeWithPatch() throws Exception {
        // Initialize the database
        insertedVariableScope = variableScopeRepository.saveAndFlush(variableScope);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the variableScope using partial update
        VariableScope partialUpdatedVariableScope = new VariableScope();
        partialUpdatedVariableScope.setId(variableScope.getId());

        partialUpdatedVariableScope.code(UPDATED_CODE).version(UPDATED_VERSION);

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

        // Validate the VariableScope in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertVariableScopeUpdatableFieldsEquals(
            createUpdateProxyForBean(partialUpdatedVariableScope, variableScope),
            getPersistedVariableScope(variableScope)
        );
    }

    @Test
    @Transactional
    void fullUpdateVariableScopeWithPatch() throws Exception {
        // Initialize the database
        insertedVariableScope = variableScopeRepository.saveAndFlush(variableScope);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the variableScope using partial update
        VariableScope partialUpdatedVariableScope = new VariableScope();
        partialUpdatedVariableScope.setId(variableScope.getId());

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

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

        // Validate the VariableScope in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertVariableScopeUpdatableFieldsEquals(partialUpdatedVariableScope, getPersistedVariableScope(partialUpdatedVariableScope));
    }

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

        // Create the VariableScope
        VariableScopeDTO variableScopeDTO = variableScopeMapper.toDto(variableScope);

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

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

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

        // Create the VariableScope
        VariableScopeDTO variableScopeDTO = variableScopeMapper.toDto(variableScope);

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

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

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

        // Create the VariableScope
        VariableScopeDTO variableScopeDTO = variableScopeMapper.toDto(variableScope);

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

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

    @Test
    @Transactional
    void deleteVariableScope() throws Exception {
        // Initialize the database
        insertedVariableScope = variableScopeRepository.saveAndFlush(variableScope);

        long databaseSizeBeforeDelete = getRepositoryCount();

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

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

    protected long getRepositoryCount() {
        return variableScopeRepository.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 VariableScope getPersistedVariableScope(VariableScope variableScope) {
        return variableScopeRepository.findById(variableScope.getId()).orElseThrow();
    }

    protected void assertPersistedVariableScopeToMatchAllProperties(VariableScope expectedVariableScope) {
        assertVariableScopeAllPropertiesEquals(expectedVariableScope, getPersistedVariableScope(expectedVariableScope));
    }

    protected void assertPersistedVariableScopeToMatchUpdatableProperties(VariableScope expectedVariableScope) {
        assertVariableScopeAllUpdatablePropertiesEquals(expectedVariableScope, getPersistedVariableScope(expectedVariableScope));
    }
}
