package com.oguerreiro.resilient.web.rest;

import static com.oguerreiro.resilient.domain.MetadataPropertyAsserts.*;
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.MetadataProperty;
import com.oguerreiro.resilient.domain.enumeration.MetadataType;
import com.oguerreiro.resilient.repository.MetadataPropertyRepository;
import com.oguerreiro.resilient.service.dto.MetadataPropertyDTO;
import com.oguerreiro.resilient.service.mapper.MetadataPropertyMapper;
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 MetadataPropertyResource} REST controller.
 */
@IntegrationTest
@AutoConfigureMockMvc
@WithMockUser
class MetadataPropertyResourceIT {

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

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

    private static final String DEFAULT_DESCRIPTION = "AAAAAAAAAA";
    private static final String UPDATED_DESCRIPTION = "BBBBBBBBBB";

    private static final Boolean DEFAULT_MANDATORY = false;
    private static final Boolean UPDATED_MANDATORY = true;

    private static final MetadataType DEFAULT_METADATA_TYPE = MetadataType.STRING;
    private static final MetadataType UPDATED_METADATA_TYPE = MetadataType.BOOLEAN;

    private static final String DEFAULT_PATTERN = "AAAAAAAAAA";
    private static final String UPDATED_PATTERN = "BBBBBBBBBB";

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

    private static final String ENTITY_API_URL = "/api/metadata-properties";
    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 MetadataPropertyRepository metadataPropertyRepository;

    @Autowired
    private MetadataPropertyMapper metadataPropertyMapper;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restMetadataPropertyMockMvc;

    private MetadataProperty metadataProperty;

    private MetadataProperty insertedMetadataProperty;

    /**
     * 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 MetadataProperty createEntity(EntityManager em) {
        MetadataProperty metadataProperty = new MetadataProperty()
            .code(DEFAULT_CODE)
            .name(DEFAULT_NAME)
            .description(DEFAULT_DESCRIPTION)
            .mandatory(DEFAULT_MANDATORY)
            .metadataType(DEFAULT_METADATA_TYPE)
            .pattern(DEFAULT_PATTERN)
            .version(DEFAULT_VERSION);
        return metadataProperty;
    }

    /**
     * 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 MetadataProperty createUpdatedEntity(EntityManager em) {
        MetadataProperty metadataProperty = new MetadataProperty()
            .code(UPDATED_CODE)
            .name(UPDATED_NAME)
            .description(UPDATED_DESCRIPTION)
            .mandatory(UPDATED_MANDATORY)
            .metadataType(UPDATED_METADATA_TYPE)
            .pattern(UPDATED_PATTERN)
            .version(UPDATED_VERSION);
        return metadataProperty;
    }

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

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

    @Test
    @Transactional
    void createMetadataProperty() throws Exception {
        long databaseSizeBeforeCreate = getRepositoryCount();
        // Create the MetadataProperty
        MetadataPropertyDTO metadataPropertyDTO = metadataPropertyMapper.toDto(metadataProperty);
        var returnedMetadataPropertyDTO = om.readValue(
            restMetadataPropertyMockMvc
                .perform(
                    post(ENTITY_API_URL)
                        .with(csrf())
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(om.writeValueAsBytes(metadataPropertyDTO))
                )
                .andExpect(status().isCreated())
                .andReturn()
                .getResponse()
                .getContentAsString(),
            MetadataPropertyDTO.class
        );

        // Validate the MetadataProperty in the database
        assertIncrementedRepositoryCount(databaseSizeBeforeCreate);
        var returnedMetadataProperty = metadataPropertyMapper.toEntity(returnedMetadataPropertyDTO);
        assertMetadataPropertyUpdatableFieldsEquals(returnedMetadataProperty, getPersistedMetadataProperty(returnedMetadataProperty));

        insertedMetadataProperty = returnedMetadataProperty;
    }

    @Test
    @Transactional
    void createMetadataPropertyWithExistingId() throws Exception {
        // Create the MetadataProperty with an existing ID
        metadataProperty.setId(1L);
        MetadataPropertyDTO metadataPropertyDTO = metadataPropertyMapper.toDto(metadataProperty);

        long databaseSizeBeforeCreate = getRepositoryCount();

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

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

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

        // Create the MetadataProperty, which fails.
        MetadataPropertyDTO metadataPropertyDTO = metadataPropertyMapper.toDto(metadataProperty);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

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

        // Create the MetadataProperty, which fails.
        MetadataPropertyDTO metadataPropertyDTO = metadataPropertyMapper.toDto(metadataProperty);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void checkMetadataTypeIsRequired() throws Exception {
        long databaseSizeBeforeTest = getRepositoryCount();
        // set the field null
        metadataProperty.setMetadataType(null);

        // Create the MetadataProperty, which fails.
        MetadataPropertyDTO metadataPropertyDTO = metadataPropertyMapper.toDto(metadataProperty);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void getAllMetadataProperties() throws Exception {
        // Initialize the database
        insertedMetadataProperty = metadataPropertyRepository.saveAndFlush(metadataProperty);

        // Get all the metadataPropertyList
        restMetadataPropertyMockMvc
            .perform(get(ENTITY_API_URL + "?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(metadataProperty.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("$.[*].mandatory").value(hasItem(DEFAULT_MANDATORY.booleanValue())))
            .andExpect(jsonPath("$.[*].metadataType").value(hasItem(DEFAULT_METADATA_TYPE.toString())))
            .andExpect(jsonPath("$.[*].pattern").value(hasItem(DEFAULT_PATTERN)))
            .andExpect(jsonPath("$.[*].version").value(hasItem(DEFAULT_VERSION)));
    }

    @Test
    @Transactional
    void getMetadataProperty() throws Exception {
        // Initialize the database
        insertedMetadataProperty = metadataPropertyRepository.saveAndFlush(metadataProperty);

        // Get the metadataProperty
        restMetadataPropertyMockMvc
            .perform(get(ENTITY_API_URL_ID, metadataProperty.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.id").value(metadataProperty.getId().intValue()))
            .andExpect(jsonPath("$.code").value(DEFAULT_CODE))
            .andExpect(jsonPath("$.name").value(DEFAULT_NAME))
            .andExpect(jsonPath("$.description").value(DEFAULT_DESCRIPTION))
            .andExpect(jsonPath("$.mandatory").value(DEFAULT_MANDATORY.booleanValue()))
            .andExpect(jsonPath("$.metadataType").value(DEFAULT_METADATA_TYPE.toString()))
            .andExpect(jsonPath("$.pattern").value(DEFAULT_PATTERN))
            .andExpect(jsonPath("$.version").value(DEFAULT_VERSION));
    }

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

    @Test
    @Transactional
    void putExistingMetadataProperty() throws Exception {
        // Initialize the database
        insertedMetadataProperty = metadataPropertyRepository.saveAndFlush(metadataProperty);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the metadataProperty
        MetadataProperty updatedMetadataProperty = metadataPropertyRepository.findById(metadataProperty.getId()).orElseThrow();
        // Disconnect from session so that the updates on updatedMetadataProperty are not directly saved in db
        em.detach(updatedMetadataProperty);
        updatedMetadataProperty
            .code(UPDATED_CODE)
            .name(UPDATED_NAME)
            .description(UPDATED_DESCRIPTION)
            .mandatory(UPDATED_MANDATORY)
            .metadataType(UPDATED_METADATA_TYPE)
            .pattern(UPDATED_PATTERN)
            .version(UPDATED_VERSION);
        MetadataPropertyDTO metadataPropertyDTO = metadataPropertyMapper.toDto(updatedMetadataProperty);

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

        // Validate the MetadataProperty in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertPersistedMetadataPropertyToMatchAllProperties(updatedMetadataProperty);
    }

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

        // Create the MetadataProperty
        MetadataPropertyDTO metadataPropertyDTO = metadataPropertyMapper.toDto(metadataProperty);

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

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

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

        // Create the MetadataProperty
        MetadataPropertyDTO metadataPropertyDTO = metadataPropertyMapper.toDto(metadataProperty);

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

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

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

        // Create the MetadataProperty
        MetadataPropertyDTO metadataPropertyDTO = metadataPropertyMapper.toDto(metadataProperty);

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

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

    @Test
    @Transactional
    void partialUpdateMetadataPropertyWithPatch() throws Exception {
        // Initialize the database
        insertedMetadataProperty = metadataPropertyRepository.saveAndFlush(metadataProperty);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the metadataProperty using partial update
        MetadataProperty partialUpdatedMetadataProperty = new MetadataProperty();
        partialUpdatedMetadataProperty.setId(metadataProperty.getId());

        partialUpdatedMetadataProperty
            .name(UPDATED_NAME)
            .mandatory(UPDATED_MANDATORY)
            .metadataType(UPDATED_METADATA_TYPE)
            .version(UPDATED_VERSION);

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

        // Validate the MetadataProperty in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertMetadataPropertyUpdatableFieldsEquals(
            createUpdateProxyForBean(partialUpdatedMetadataProperty, metadataProperty),
            getPersistedMetadataProperty(metadataProperty)
        );
    }

    @Test
    @Transactional
    void fullUpdateMetadataPropertyWithPatch() throws Exception {
        // Initialize the database
        insertedMetadataProperty = metadataPropertyRepository.saveAndFlush(metadataProperty);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the metadataProperty using partial update
        MetadataProperty partialUpdatedMetadataProperty = new MetadataProperty();
        partialUpdatedMetadataProperty.setId(metadataProperty.getId());

        partialUpdatedMetadataProperty
            .code(UPDATED_CODE)
            .name(UPDATED_NAME)
            .description(UPDATED_DESCRIPTION)
            .mandatory(UPDATED_MANDATORY)
            .metadataType(UPDATED_METADATA_TYPE)
            .pattern(UPDATED_PATTERN)
            .version(UPDATED_VERSION);

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

        // Validate the MetadataProperty in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertMetadataPropertyUpdatableFieldsEquals(
            partialUpdatedMetadataProperty,
            getPersistedMetadataProperty(partialUpdatedMetadataProperty)
        );
    }

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

        // Create the MetadataProperty
        MetadataPropertyDTO metadataPropertyDTO = metadataPropertyMapper.toDto(metadataProperty);

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

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

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

        // Create the MetadataProperty
        MetadataPropertyDTO metadataPropertyDTO = metadataPropertyMapper.toDto(metadataProperty);

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

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

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

        // Create the MetadataProperty
        MetadataPropertyDTO metadataPropertyDTO = metadataPropertyMapper.toDto(metadataProperty);

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

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

    @Test
    @Transactional
    void deleteMetadataProperty() throws Exception {
        // Initialize the database
        insertedMetadataProperty = metadataPropertyRepository.saveAndFlush(metadataProperty);

        long databaseSizeBeforeDelete = getRepositoryCount();

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

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

    protected long getRepositoryCount() {
        return metadataPropertyRepository.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 MetadataProperty getPersistedMetadataProperty(MetadataProperty metadataProperty) {
        return metadataPropertyRepository.findById(metadataProperty.getId()).orElseThrow();
    }

    protected void assertPersistedMetadataPropertyToMatchAllProperties(MetadataProperty expectedMetadataProperty) {
        assertMetadataPropertyAllPropertiesEquals(expectedMetadataProperty, getPersistedMetadataProperty(expectedMetadataProperty));
    }

    protected void assertPersistedMetadataPropertyToMatchUpdatableProperties(MetadataProperty expectedMetadataProperty) {
        assertMetadataPropertyAllUpdatablePropertiesEquals(
            expectedMetadataProperty,
            getPersistedMetadataProperty(expectedMetadataProperty)
        );
    }
}
