package com.oguerreiro.resilient.web.rest;

import static com.oguerreiro.resilient.domain.VariableAsserts.*;
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.Unit;
import com.oguerreiro.resilient.domain.Variable;
import com.oguerreiro.resilient.domain.VariableCategory;
import com.oguerreiro.resilient.domain.VariableScope;
import com.oguerreiro.resilient.domain.enumeration.InputMode;
import com.oguerreiro.resilient.repository.VariableRepository;
import com.oguerreiro.resilient.service.VariableService;
import com.oguerreiro.resilient.service.dto.VariableDTO;
import com.oguerreiro.resilient.service.mapper.VariableMapper;
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 VariableResource} REST controller.
 */
@IntegrationTest
@ExtendWith(MockitoExtension.class)
@AutoConfigureMockMvc
@WithMockUser
class VariableResourceIT {

    private static final String DEFAULT_CODE = "";
    private static final String UPDATED_CODE = "1";

    private static final Integer DEFAULT_VARIABLE_INDEX = 1;
    private static final Integer UPDATED_VARIABLE_INDEX = 2;
    private static final Integer SMALLER_VARIABLE_INDEX = 1 - 1;

    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 Boolean DEFAULT_INPUT = false;
    private static final Boolean UPDATED_INPUT = true;

    private static final InputMode DEFAULT_INPUT_MODE = InputMode.DATAFILE;
    private static final InputMode UPDATED_INPUT_MODE = InputMode.MANUAL;

    private static final Boolean DEFAULT_OUTPUT = false;
    private static final Boolean UPDATED_OUTPUT = true;

    private static final String DEFAULT_OUTPUT_FORMULA = "AAAAAAAAAA";
    private static final String UPDATED_OUTPUT_FORMULA = "BBBBBBBBBB";

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

    private static final String ENTITY_API_URL = "/api/variables";
    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 VariableRepository variableRepository;

    @Mock
    private VariableRepository variableRepositoryMock;

    @Autowired
    private VariableMapper variableMapper;

    @Mock
    private VariableService variableServiceMock;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restVariableMockMvc;

    private Variable variable;

    private Variable insertedVariable;

    /**
     * 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 Variable createEntity(EntityManager em) {
        Variable variable = new Variable()
            .code(DEFAULT_CODE)
            .variableIndex(DEFAULT_VARIABLE_INDEX)
            .name(DEFAULT_NAME)
            .description(DEFAULT_DESCRIPTION)
            .input(DEFAULT_INPUT)
            .inputMode(DEFAULT_INPUT_MODE)
            .output(DEFAULT_OUTPUT)
            .outputFormula(DEFAULT_OUTPUT_FORMULA)
            .version(DEFAULT_VERSION);
        return variable;
    }

    /**
     * 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 Variable createUpdatedEntity(EntityManager em) {
        Variable variable = new Variable()
            .code(UPDATED_CODE)
            .variableIndex(UPDATED_VARIABLE_INDEX)
            .name(UPDATED_NAME)
            .description(UPDATED_DESCRIPTION)
            .input(UPDATED_INPUT)
            .inputMode(UPDATED_INPUT_MODE)
            .output(UPDATED_OUTPUT)
            .outputFormula(UPDATED_OUTPUT_FORMULA)
            .version(UPDATED_VERSION);
        return variable;
    }

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

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

    @Test
    @Transactional
    void createVariable() throws Exception {
        long databaseSizeBeforeCreate = getRepositoryCount();
        // Create the Variable
        VariableDTO variableDTO = variableMapper.toDto(variable);
        var returnedVariableDTO = om.readValue(
            restVariableMockMvc
                .perform(
                    post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(variableDTO))
                )
                .andExpect(status().isCreated())
                .andReturn()
                .getResponse()
                .getContentAsString(),
            VariableDTO.class
        );

        // Validate the Variable in the database
        assertIncrementedRepositoryCount(databaseSizeBeforeCreate);
        var returnedVariable = variableMapper.toEntity(returnedVariableDTO);
        assertVariableUpdatableFieldsEquals(returnedVariable, getPersistedVariable(returnedVariable));

        insertedVariable = returnedVariable;
    }

    @Test
    @Transactional
    void createVariableWithExistingId() throws Exception {
        // Create the Variable with an existing ID
        variable.setId(1L);
        VariableDTO variableDTO = variableMapper.toDto(variable);

        long databaseSizeBeforeCreate = getRepositoryCount();

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

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

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

        // Create the Variable, which fails.
        VariableDTO variableDTO = variableMapper.toDto(variable);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void checkVariableIndexIsRequired() throws Exception {
        long databaseSizeBeforeTest = getRepositoryCount();
        // set the field null
        variable.setVariableIndex(null);

        // Create the Variable, which fails.
        VariableDTO variableDTO = variableMapper.toDto(variable);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

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

        // Create the Variable, which fails.
        VariableDTO variableDTO = variableMapper.toDto(variable);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

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

        // Create the Variable, which fails.
        VariableDTO variableDTO = variableMapper.toDto(variable);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void checkInputIsRequired() throws Exception {
        long databaseSizeBeforeTest = getRepositoryCount();
        // set the field null
        variable.setInput(null);

        // Create the Variable, which fails.
        VariableDTO variableDTO = variableMapper.toDto(variable);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void checkInputModeIsRequired() throws Exception {
        long databaseSizeBeforeTest = getRepositoryCount();
        // set the field null
        variable.setInputMode(null);

        // Create the Variable, which fails.
        VariableDTO variableDTO = variableMapper.toDto(variable);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void checkOutputIsRequired() throws Exception {
        long databaseSizeBeforeTest = getRepositoryCount();
        // set the field null
        variable.setOutput(null);

        // Create the Variable, which fails.
        VariableDTO variableDTO = variableMapper.toDto(variable);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void getAllVariables() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList
        restVariableMockMvc
            .perform(get(ENTITY_API_URL + "?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(variable.getId().intValue())))
            .andExpect(jsonPath("$.[*].code").value(hasItem(DEFAULT_CODE)))
            .andExpect(jsonPath("$.[*].variableIndex").value(hasItem(DEFAULT_VARIABLE_INDEX)))
            .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME)))
            .andExpect(jsonPath("$.[*].description").value(hasItem(DEFAULT_DESCRIPTION)))
            .andExpect(jsonPath("$.[*].input").value(hasItem(DEFAULT_INPUT.booleanValue())))
            .andExpect(jsonPath("$.[*].inputMode").value(hasItem(DEFAULT_INPUT_MODE.toString())))
            .andExpect(jsonPath("$.[*].output").value(hasItem(DEFAULT_OUTPUT.booleanValue())))
            .andExpect(jsonPath("$.[*].outputFormula").value(hasItem(DEFAULT_OUTPUT_FORMULA)))
            .andExpect(jsonPath("$.[*].version").value(hasItem(DEFAULT_VERSION)));
    }

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

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

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

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

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

    @Test
    @Transactional
    void getVariable() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get the variable
        restVariableMockMvc
            .perform(get(ENTITY_API_URL_ID, variable.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.id").value(variable.getId().intValue()))
            .andExpect(jsonPath("$.code").value(DEFAULT_CODE))
            .andExpect(jsonPath("$.variableIndex").value(DEFAULT_VARIABLE_INDEX))
            .andExpect(jsonPath("$.name").value(DEFAULT_NAME))
            .andExpect(jsonPath("$.description").value(DEFAULT_DESCRIPTION))
            .andExpect(jsonPath("$.input").value(DEFAULT_INPUT.booleanValue()))
            .andExpect(jsonPath("$.inputMode").value(DEFAULT_INPUT_MODE.toString()))
            .andExpect(jsonPath("$.output").value(DEFAULT_OUTPUT.booleanValue()))
            .andExpect(jsonPath("$.outputFormula").value(DEFAULT_OUTPUT_FORMULA))
            .andExpect(jsonPath("$.version").value(DEFAULT_VERSION));
    }

    @Test
    @Transactional
    void getVariablesByIdFiltering() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        Long id = variable.getId();

        defaultVariableFiltering("id.equals=" + id, "id.notEquals=" + id);

        defaultVariableFiltering("id.greaterThanOrEqual=" + id, "id.greaterThan=" + id);

        defaultVariableFiltering("id.lessThanOrEqual=" + id, "id.lessThan=" + id);
    }

    @Test
    @Transactional
    void getAllVariablesByCodeIsEqualToSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where code equals to
        defaultVariableFiltering("code.equals=" + DEFAULT_CODE, "code.equals=" + UPDATED_CODE);
    }

    @Test
    @Transactional
    void getAllVariablesByCodeIsInShouldWork() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where code in
        defaultVariableFiltering("code.in=" + DEFAULT_CODE + "," + UPDATED_CODE, "code.in=" + UPDATED_CODE);
    }

    @Test
    @Transactional
    void getAllVariablesByCodeIsNullOrNotNull() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where code is not null
        defaultVariableFiltering("code.specified=true", "code.specified=false");
    }

    @Test
    @Transactional
    void getAllVariablesByCodeContainsSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where code contains
        defaultVariableFiltering("code.contains=" + DEFAULT_CODE, "code.contains=" + UPDATED_CODE);
    }

    @Test
    @Transactional
    void getAllVariablesByCodeNotContainsSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where code does not contain
        defaultVariableFiltering("code.doesNotContain=" + UPDATED_CODE, "code.doesNotContain=" + DEFAULT_CODE);
    }

    @Test
    @Transactional
    void getAllVariablesByVariableIndexIsEqualToSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where variableIndex equals to
        defaultVariableFiltering("variableIndex.equals=" + DEFAULT_VARIABLE_INDEX, "variableIndex.equals=" + UPDATED_VARIABLE_INDEX);
    }

    @Test
    @Transactional
    void getAllVariablesByVariableIndexIsInShouldWork() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where variableIndex in
        defaultVariableFiltering(
            "variableIndex.in=" + DEFAULT_VARIABLE_INDEX + "," + UPDATED_VARIABLE_INDEX,
            "variableIndex.in=" + UPDATED_VARIABLE_INDEX
        );
    }

    @Test
    @Transactional
    void getAllVariablesByVariableIndexIsNullOrNotNull() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where variableIndex is not null
        defaultVariableFiltering("variableIndex.specified=true", "variableIndex.specified=false");
    }

    @Test
    @Transactional
    void getAllVariablesByVariableIndexIsGreaterThanOrEqualToSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where variableIndex is greater than or equal to
        defaultVariableFiltering(
            "variableIndex.greaterThanOrEqual=" + DEFAULT_VARIABLE_INDEX,
            "variableIndex.greaterThanOrEqual=" + UPDATED_VARIABLE_INDEX
        );
    }

    @Test
    @Transactional
    void getAllVariablesByVariableIndexIsLessThanOrEqualToSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where variableIndex is less than or equal to
        defaultVariableFiltering(
            "variableIndex.lessThanOrEqual=" + DEFAULT_VARIABLE_INDEX,
            "variableIndex.lessThanOrEqual=" + SMALLER_VARIABLE_INDEX
        );
    }

    @Test
    @Transactional
    void getAllVariablesByVariableIndexIsLessThanSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where variableIndex is less than
        defaultVariableFiltering("variableIndex.lessThan=" + UPDATED_VARIABLE_INDEX, "variableIndex.lessThan=" + DEFAULT_VARIABLE_INDEX);
    }

    @Test
    @Transactional
    void getAllVariablesByVariableIndexIsGreaterThanSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where variableIndex is greater than
        defaultVariableFiltering(
            "variableIndex.greaterThan=" + SMALLER_VARIABLE_INDEX,
            "variableIndex.greaterThan=" + DEFAULT_VARIABLE_INDEX
        );
    }

    @Test
    @Transactional
    void getAllVariablesByNameIsEqualToSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where name equals to
        defaultVariableFiltering("name.equals=" + DEFAULT_NAME, "name.equals=" + UPDATED_NAME);
    }

    @Test
    @Transactional
    void getAllVariablesByNameIsInShouldWork() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where name in
        defaultVariableFiltering("name.in=" + DEFAULT_NAME + "," + UPDATED_NAME, "name.in=" + UPDATED_NAME);
    }

    @Test
    @Transactional
    void getAllVariablesByNameIsNullOrNotNull() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where name is not null
        defaultVariableFiltering("name.specified=true", "name.specified=false");
    }

    @Test
    @Transactional
    void getAllVariablesByNameContainsSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where name contains
        defaultVariableFiltering("name.contains=" + DEFAULT_NAME, "name.contains=" + UPDATED_NAME);
    }

    @Test
    @Transactional
    void getAllVariablesByNameNotContainsSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where name does not contain
        defaultVariableFiltering("name.doesNotContain=" + UPDATED_NAME, "name.doesNotContain=" + DEFAULT_NAME);
    }

    @Test
    @Transactional
    void getAllVariablesByDescriptionIsEqualToSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where description equals to
        defaultVariableFiltering("description.equals=" + DEFAULT_DESCRIPTION, "description.equals=" + UPDATED_DESCRIPTION);
    }

    @Test
    @Transactional
    void getAllVariablesByDescriptionIsInShouldWork() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where description in
        defaultVariableFiltering(
            "description.in=" + DEFAULT_DESCRIPTION + "," + UPDATED_DESCRIPTION,
            "description.in=" + UPDATED_DESCRIPTION
        );
    }

    @Test
    @Transactional
    void getAllVariablesByDescriptionIsNullOrNotNull() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where description is not null
        defaultVariableFiltering("description.specified=true", "description.specified=false");
    }

    @Test
    @Transactional
    void getAllVariablesByDescriptionContainsSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where description contains
        defaultVariableFiltering("description.contains=" + DEFAULT_DESCRIPTION, "description.contains=" + UPDATED_DESCRIPTION);
    }

    @Test
    @Transactional
    void getAllVariablesByDescriptionNotContainsSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where description does not contain
        defaultVariableFiltering("description.doesNotContain=" + UPDATED_DESCRIPTION, "description.doesNotContain=" + DEFAULT_DESCRIPTION);
    }

    @Test
    @Transactional
    void getAllVariablesByInputIsEqualToSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where input equals to
        defaultVariableFiltering("input.equals=" + DEFAULT_INPUT, "input.equals=" + UPDATED_INPUT);
    }

    @Test
    @Transactional
    void getAllVariablesByInputIsInShouldWork() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where input in
        defaultVariableFiltering("input.in=" + DEFAULT_INPUT + "," + UPDATED_INPUT, "input.in=" + UPDATED_INPUT);
    }

    @Test
    @Transactional
    void getAllVariablesByInputIsNullOrNotNull() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where input is not null
        defaultVariableFiltering("input.specified=true", "input.specified=false");
    }

    @Test
    @Transactional
    void getAllVariablesByInputModeIsEqualToSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where inputMode equals to
        defaultVariableFiltering("inputMode.equals=" + DEFAULT_INPUT_MODE, "inputMode.equals=" + UPDATED_INPUT_MODE);
    }

    @Test
    @Transactional
    void getAllVariablesByInputModeIsInShouldWork() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where inputMode in
        defaultVariableFiltering("inputMode.in=" + DEFAULT_INPUT_MODE + "," + UPDATED_INPUT_MODE, "inputMode.in=" + UPDATED_INPUT_MODE);
    }

    @Test
    @Transactional
    void getAllVariablesByInputModeIsNullOrNotNull() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where inputMode is not null
        defaultVariableFiltering("inputMode.specified=true", "inputMode.specified=false");
    }

    @Test
    @Transactional
    void getAllVariablesByOutputIsEqualToSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where output equals to
        defaultVariableFiltering("output.equals=" + DEFAULT_OUTPUT, "output.equals=" + UPDATED_OUTPUT);
    }

    @Test
    @Transactional
    void getAllVariablesByOutputIsInShouldWork() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where output in
        defaultVariableFiltering("output.in=" + DEFAULT_OUTPUT + "," + UPDATED_OUTPUT, "output.in=" + UPDATED_OUTPUT);
    }

    @Test
    @Transactional
    void getAllVariablesByOutputIsNullOrNotNull() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where output is not null
        defaultVariableFiltering("output.specified=true", "output.specified=false");
    }

    @Test
    @Transactional
    void getAllVariablesByOutputFormulaIsEqualToSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where outputFormula equals to
        defaultVariableFiltering("outputFormula.equals=" + DEFAULT_OUTPUT_FORMULA, "outputFormula.equals=" + UPDATED_OUTPUT_FORMULA);
    }

    @Test
    @Transactional
    void getAllVariablesByOutputFormulaIsInShouldWork() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where outputFormula in
        defaultVariableFiltering(
            "outputFormula.in=" + DEFAULT_OUTPUT_FORMULA + "," + UPDATED_OUTPUT_FORMULA,
            "outputFormula.in=" + UPDATED_OUTPUT_FORMULA
        );
    }

    @Test
    @Transactional
    void getAllVariablesByOutputFormulaIsNullOrNotNull() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where outputFormula is not null
        defaultVariableFiltering("outputFormula.specified=true", "outputFormula.specified=false");
    }

    @Test
    @Transactional
    void getAllVariablesByOutputFormulaContainsSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where outputFormula contains
        defaultVariableFiltering("outputFormula.contains=" + DEFAULT_OUTPUT_FORMULA, "outputFormula.contains=" + UPDATED_OUTPUT_FORMULA);
    }

    @Test
    @Transactional
    void getAllVariablesByOutputFormulaNotContainsSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where outputFormula does not contain
        defaultVariableFiltering(
            "outputFormula.doesNotContain=" + UPDATED_OUTPUT_FORMULA,
            "outputFormula.doesNotContain=" + DEFAULT_OUTPUT_FORMULA
        );
    }

    @Test
    @Transactional
    void getAllVariablesByVersionIsEqualToSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where version equals to
        defaultVariableFiltering("version.equals=" + DEFAULT_VERSION, "version.equals=" + UPDATED_VERSION);
    }

    @Test
    @Transactional
    void getAllVariablesByVersionIsInShouldWork() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where version in
        defaultVariableFiltering("version.in=" + DEFAULT_VERSION + "," + UPDATED_VERSION, "version.in=" + UPDATED_VERSION);
    }

    @Test
    @Transactional
    void getAllVariablesByVersionIsNullOrNotNull() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where version is not null
        defaultVariableFiltering("version.specified=true", "version.specified=false");
    }

    @Test
    @Transactional
    void getAllVariablesByVersionIsGreaterThanOrEqualToSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where version is greater than or equal to
        defaultVariableFiltering("version.greaterThanOrEqual=" + DEFAULT_VERSION, "version.greaterThanOrEqual=" + UPDATED_VERSION);
    }

    @Test
    @Transactional
    void getAllVariablesByVersionIsLessThanOrEqualToSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where version is less than or equal to
        defaultVariableFiltering("version.lessThanOrEqual=" + DEFAULT_VERSION, "version.lessThanOrEqual=" + SMALLER_VERSION);
    }

    @Test
    @Transactional
    void getAllVariablesByVersionIsLessThanSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where version is less than
        defaultVariableFiltering("version.lessThan=" + UPDATED_VERSION, "version.lessThan=" + DEFAULT_VERSION);
    }

    @Test
    @Transactional
    void getAllVariablesByVersionIsGreaterThanSomething() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        // Get all the variableList where version is greater than
        defaultVariableFiltering("version.greaterThan=" + SMALLER_VERSION, "version.greaterThan=" + DEFAULT_VERSION);
    }

    @Test
    @Transactional
    void getAllVariablesByBaseUnitIsEqualToSomething() throws Exception {
        Unit baseUnit;
        if (TestUtil.findAll(em, Unit.class).isEmpty()) {
            variableRepository.saveAndFlush(variable);
            baseUnit = UnitResourceIT.createEntity(em);
        } else {
            baseUnit = TestUtil.findAll(em, Unit.class).get(0);
        }
        em.persist(baseUnit);
        em.flush();
        variable.setBaseUnit(baseUnit);
        variableRepository.saveAndFlush(variable);
        Long baseUnitId = baseUnit.getId();
        // Get all the variableList where baseUnit equals to baseUnitId
        defaultVariableShouldBeFound("baseUnitId.equals=" + baseUnitId);

        // Get all the variableList where baseUnit equals to (baseUnitId + 1)
        defaultVariableShouldNotBeFound("baseUnitId.equals=" + (baseUnitId + 1));
    }

    @Test
    @Transactional
    void getAllVariablesByVariableScopeIsEqualToSomething() throws Exception {
        VariableScope variableScope;
        if (TestUtil.findAll(em, VariableScope.class).isEmpty()) {
            variableRepository.saveAndFlush(variable);
            variableScope = VariableScopeResourceIT.createEntity(em);
        } else {
            variableScope = TestUtil.findAll(em, VariableScope.class).get(0);
        }
        em.persist(variableScope);
        em.flush();
        variable.setVariableScope(variableScope);
        variableRepository.saveAndFlush(variable);
        Long variableScopeId = variableScope.getId();
        // Get all the variableList where variableScope equals to variableScopeId
        defaultVariableShouldBeFound("variableScopeId.equals=" + variableScopeId);

        // Get all the variableList where variableScope equals to (variableScopeId + 1)
        defaultVariableShouldNotBeFound("variableScopeId.equals=" + (variableScopeId + 1));
    }

    @Test
    @Transactional
    void getAllVariablesByVariableCategoryIsEqualToSomething() throws Exception {
        VariableCategory variableCategory;
        if (TestUtil.findAll(em, VariableCategory.class).isEmpty()) {
            variableRepository.saveAndFlush(variable);
            variableCategory = VariableCategoryResourceIT.createEntity(em);
        } else {
            variableCategory = TestUtil.findAll(em, VariableCategory.class).get(0);
        }
        em.persist(variableCategory);
        em.flush();
        variable.setVariableCategory(variableCategory);
        variableRepository.saveAndFlush(variable);
        Long variableCategoryId = variableCategory.getId();
        // Get all the variableList where variableCategory equals to variableCategoryId
        defaultVariableShouldBeFound("variableCategoryId.equals=" + variableCategoryId);

        // Get all the variableList where variableCategory equals to (variableCategoryId + 1)
        defaultVariableShouldNotBeFound("variableCategoryId.equals=" + (variableCategoryId + 1));
    }

    private void defaultVariableFiltering(String shouldBeFound, String shouldNotBeFound) throws Exception {
        defaultVariableShouldBeFound(shouldBeFound);
        defaultVariableShouldNotBeFound(shouldNotBeFound);
    }

    /**
     * Executes the search, and checks that the default entity is returned.
     */
    private void defaultVariableShouldBeFound(String filter) throws Exception {
        restVariableMockMvc
            .perform(get(ENTITY_API_URL + "?sort=id,desc&" + filter))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(variable.getId().intValue())))
            .andExpect(jsonPath("$.[*].code").value(hasItem(DEFAULT_CODE)))
            .andExpect(jsonPath("$.[*].variableIndex").value(hasItem(DEFAULT_VARIABLE_INDEX)))
            .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME)))
            .andExpect(jsonPath("$.[*].description").value(hasItem(DEFAULT_DESCRIPTION)))
            .andExpect(jsonPath("$.[*].input").value(hasItem(DEFAULT_INPUT.booleanValue())))
            .andExpect(jsonPath("$.[*].inputMode").value(hasItem(DEFAULT_INPUT_MODE.toString())))
            .andExpect(jsonPath("$.[*].output").value(hasItem(DEFAULT_OUTPUT.booleanValue())))
            .andExpect(jsonPath("$.[*].outputFormula").value(hasItem(DEFAULT_OUTPUT_FORMULA)))
            .andExpect(jsonPath("$.[*].version").value(hasItem(DEFAULT_VERSION)));

        // Check, that the count call also returns 1
        restVariableMockMvc
            .perform(get(ENTITY_API_URL + "/count?sort=id,desc&" + filter))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(content().string("1"));
    }

    /**
     * Executes the search, and checks that the default entity is not returned.
     */
    private void defaultVariableShouldNotBeFound(String filter) throws Exception {
        restVariableMockMvc
            .perform(get(ENTITY_API_URL + "?sort=id,desc&" + filter))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$").isArray())
            .andExpect(jsonPath("$").isEmpty());

        // Check, that the count call also returns 0
        restVariableMockMvc
            .perform(get(ENTITY_API_URL + "/count?sort=id,desc&" + filter))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(content().string("0"));
    }

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

    @Test
    @Transactional
    void putExistingVariable() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the variable
        Variable updatedVariable = variableRepository.findById(variable.getId()).orElseThrow();
        // Disconnect from session so that the updates on updatedVariable are not directly saved in db
        em.detach(updatedVariable);
        updatedVariable
            .code(UPDATED_CODE)
            .variableIndex(UPDATED_VARIABLE_INDEX)
            .name(UPDATED_NAME)
            .description(UPDATED_DESCRIPTION)
            .input(UPDATED_INPUT)
            .inputMode(UPDATED_INPUT_MODE)
            .output(UPDATED_OUTPUT)
            .outputFormula(UPDATED_OUTPUT_FORMULA)
            .version(UPDATED_VERSION);
        VariableDTO variableDTO = variableMapper.toDto(updatedVariable);

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

        // Validate the Variable in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertPersistedVariableToMatchAllProperties(updatedVariable);
    }

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

        // Create the Variable
        VariableDTO variableDTO = variableMapper.toDto(variable);

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

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

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

        // Create the Variable
        VariableDTO variableDTO = variableMapper.toDto(variable);

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

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

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

        // Create the Variable
        VariableDTO variableDTO = variableMapper.toDto(variable);

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

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

    @Test
    @Transactional
    void partialUpdateVariableWithPatch() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the variable using partial update
        Variable partialUpdatedVariable = new Variable();
        partialUpdatedVariable.setId(variable.getId());

        partialUpdatedVariable
            .variableIndex(UPDATED_VARIABLE_INDEX)
            .description(UPDATED_DESCRIPTION)
            .input(UPDATED_INPUT)
            .output(UPDATED_OUTPUT)
            .outputFormula(UPDATED_OUTPUT_FORMULA);

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

        // Validate the Variable in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertVariableUpdatableFieldsEquals(createUpdateProxyForBean(partialUpdatedVariable, variable), getPersistedVariable(variable));
    }

    @Test
    @Transactional
    void fullUpdateVariableWithPatch() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the variable using partial update
        Variable partialUpdatedVariable = new Variable();
        partialUpdatedVariable.setId(variable.getId());

        partialUpdatedVariable
            .code(UPDATED_CODE)
            .variableIndex(UPDATED_VARIABLE_INDEX)
            .name(UPDATED_NAME)
            .description(UPDATED_DESCRIPTION)
            .input(UPDATED_INPUT)
            .inputMode(UPDATED_INPUT_MODE)
            .output(UPDATED_OUTPUT)
            .outputFormula(UPDATED_OUTPUT_FORMULA)
            .version(UPDATED_VERSION);

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

        // Validate the Variable in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertVariableUpdatableFieldsEquals(partialUpdatedVariable, getPersistedVariable(partialUpdatedVariable));
    }

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

        // Create the Variable
        VariableDTO variableDTO = variableMapper.toDto(variable);

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

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

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

        // Create the Variable
        VariableDTO variableDTO = variableMapper.toDto(variable);

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

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

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

        // Create the Variable
        VariableDTO variableDTO = variableMapper.toDto(variable);

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

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

    @Test
    @Transactional
    void deleteVariable() throws Exception {
        // Initialize the database
        insertedVariable = variableRepository.saveAndFlush(variable);

        long databaseSizeBeforeDelete = getRepositoryCount();

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

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

    protected long getRepositoryCount() {
        return variableRepository.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 Variable getPersistedVariable(Variable variable) {
        return variableRepository.findById(variable.getId()).orElseThrow();
    }

    protected void assertPersistedVariableToMatchAllProperties(Variable expectedVariable) {
        assertVariableAllPropertiesEquals(expectedVariable, getPersistedVariable(expectedVariable));
    }

    protected void assertPersistedVariableToMatchUpdatableProperties(Variable expectedVariable) {
        assertVariableAllUpdatablePropertiesEquals(expectedVariable, getPersistedVariable(expectedVariable));
    }
}
