package com.oguerreiro.resilient.web.rest;

import static com.oguerreiro.resilient.domain.MetadataValueAsserts.*;
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.MetadataValue;
import com.oguerreiro.resilient.repository.MetadataValueRepository;
import com.oguerreiro.resilient.service.dto.MetadataValueDTO;
import com.oguerreiro.resilient.service.mapper.MetadataValueMapper;
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 MetadataValueResource} REST controller.
 */
@IntegrationTest
@AutoConfigureMockMvc
@WithMockUser
class MetadataValueResourceIT {

    private static final String DEFAULT_METADATA_PROPERTY_CODE = "AAAAAAAAAA";
    private static final String UPDATED_METADATA_PROPERTY_CODE = "BBBBBBBBBB";

    private static final String DEFAULT_TARGET_DOMAIN_KEY = "AAAAAAAAAA";
    private static final String UPDATED_TARGET_DOMAIN_KEY = "BBBBBBBBBB";

    private static final Long DEFAULT_TARGET_DOMAIN_ID = 1L;
    private static final Long UPDATED_TARGET_DOMAIN_ID = 2L;

    private static final String DEFAULT_VALUE = "AAAAAAAAAA";
    private static final String UPDATED_VALUE = "BBBBBBBBBB";

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

    private static final String ENTITY_API_URL = "/api/metadata-values";
    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 MetadataValueRepository metadataValueRepository;

    @Autowired
    private MetadataValueMapper metadataValueMapper;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restMetadataValueMockMvc;

    private MetadataValue metadataValue;

    private MetadataValue insertedMetadataValue;

    /**
     * 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 MetadataValue createEntity(EntityManager em) {
        MetadataValue metadataValue = new MetadataValue()
            .metadataPropertyCode(DEFAULT_METADATA_PROPERTY_CODE)
            .targetDomainKey(DEFAULT_TARGET_DOMAIN_KEY)
            .targetDomainId(DEFAULT_TARGET_DOMAIN_ID)
            .value(DEFAULT_VALUE)
            .version(DEFAULT_VERSION);
        return metadataValue;
    }

    /**
     * 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 MetadataValue createUpdatedEntity(EntityManager em) {
        MetadataValue metadataValue = new MetadataValue()
            .metadataPropertyCode(UPDATED_METADATA_PROPERTY_CODE)
            .targetDomainKey(UPDATED_TARGET_DOMAIN_KEY)
            .targetDomainId(UPDATED_TARGET_DOMAIN_ID)
            .value(UPDATED_VALUE)
            .version(UPDATED_VERSION);
        return metadataValue;
    }

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

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

    @Test
    @Transactional
    void createMetadataValue() throws Exception {
        long databaseSizeBeforeCreate = getRepositoryCount();
        // Create the MetadataValue
        MetadataValueDTO metadataValueDTO = metadataValueMapper.toDto(metadataValue);
        var returnedMetadataValueDTO = om.readValue(
            restMetadataValueMockMvc
                .perform(
                    post(ENTITY_API_URL)
                        .with(csrf())
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(om.writeValueAsBytes(metadataValueDTO))
                )
                .andExpect(status().isCreated())
                .andReturn()
                .getResponse()
                .getContentAsString(),
            MetadataValueDTO.class
        );

        // Validate the MetadataValue in the database
        assertIncrementedRepositoryCount(databaseSizeBeforeCreate);
        var returnedMetadataValue = metadataValueMapper.toEntity(returnedMetadataValueDTO);
        assertMetadataValueUpdatableFieldsEquals(returnedMetadataValue, getPersistedMetadataValue(returnedMetadataValue));

        insertedMetadataValue = returnedMetadataValue;
    }

    @Test
    @Transactional
    void createMetadataValueWithExistingId() throws Exception {
        // Create the MetadataValue with an existing ID
        metadataValue.setId(1L);
        MetadataValueDTO metadataValueDTO = metadataValueMapper.toDto(metadataValue);

        long databaseSizeBeforeCreate = getRepositoryCount();

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

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

    @Test
    @Transactional
    void checkMetadataPropertyCodeIsRequired() throws Exception {
        long databaseSizeBeforeTest = getRepositoryCount();
        // set the field null
        metadataValue.setMetadataPropertyCode(null);

        // Create the MetadataValue, which fails.
        MetadataValueDTO metadataValueDTO = metadataValueMapper.toDto(metadataValue);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void checkTargetDomainKeyIsRequired() throws Exception {
        long databaseSizeBeforeTest = getRepositoryCount();
        // set the field null
        metadataValue.setTargetDomainKey(null);

        // Create the MetadataValue, which fails.
        MetadataValueDTO metadataValueDTO = metadataValueMapper.toDto(metadataValue);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void checkTargetDomainIdIsRequired() throws Exception {
        long databaseSizeBeforeTest = getRepositoryCount();
        // set the field null
        metadataValue.setTargetDomainId(null);

        // Create the MetadataValue, which fails.
        MetadataValueDTO metadataValueDTO = metadataValueMapper.toDto(metadataValue);

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

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void getAllMetadataValues() throws Exception {
        // Initialize the database
        insertedMetadataValue = metadataValueRepository.saveAndFlush(metadataValue);

        // Get all the metadataValueList
        restMetadataValueMockMvc
            .perform(get(ENTITY_API_URL + "?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(metadataValue.getId().intValue())))
            .andExpect(jsonPath("$.[*].metadataPropertyCode").value(hasItem(DEFAULT_METADATA_PROPERTY_CODE)))
            .andExpect(jsonPath("$.[*].targetDomainKey").value(hasItem(DEFAULT_TARGET_DOMAIN_KEY)))
            .andExpect(jsonPath("$.[*].targetDomainId").value(hasItem(DEFAULT_TARGET_DOMAIN_ID.intValue())))
            .andExpect(jsonPath("$.[*].value").value(hasItem(DEFAULT_VALUE)))
            .andExpect(jsonPath("$.[*].version").value(hasItem(DEFAULT_VERSION)));
    }

    @Test
    @Transactional
    void getMetadataValue() throws Exception {
        // Initialize the database
        insertedMetadataValue = metadataValueRepository.saveAndFlush(metadataValue);

        // Get the metadataValue
        restMetadataValueMockMvc
            .perform(get(ENTITY_API_URL_ID, metadataValue.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.id").value(metadataValue.getId().intValue()))
            .andExpect(jsonPath("$.metadataPropertyCode").value(DEFAULT_METADATA_PROPERTY_CODE))
            .andExpect(jsonPath("$.targetDomainKey").value(DEFAULT_TARGET_DOMAIN_KEY))
            .andExpect(jsonPath("$.targetDomainId").value(DEFAULT_TARGET_DOMAIN_ID.intValue()))
            .andExpect(jsonPath("$.value").value(DEFAULT_VALUE))
            .andExpect(jsonPath("$.version").value(DEFAULT_VERSION));
    }

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

    @Test
    @Transactional
    void putExistingMetadataValue() throws Exception {
        // Initialize the database
        insertedMetadataValue = metadataValueRepository.saveAndFlush(metadataValue);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the metadataValue
        MetadataValue updatedMetadataValue = metadataValueRepository.findById(metadataValue.getId()).orElseThrow();
        // Disconnect from session so that the updates on updatedMetadataValue are not directly saved in db
        em.detach(updatedMetadataValue);
        updatedMetadataValue
            .metadataPropertyCode(UPDATED_METADATA_PROPERTY_CODE)
            .targetDomainKey(UPDATED_TARGET_DOMAIN_KEY)
            .targetDomainId(UPDATED_TARGET_DOMAIN_ID)
            .value(UPDATED_VALUE)
            .version(UPDATED_VERSION);
        MetadataValueDTO metadataValueDTO = metadataValueMapper.toDto(updatedMetadataValue);

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

        // Validate the MetadataValue in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertPersistedMetadataValueToMatchAllProperties(updatedMetadataValue);
    }

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

        // Create the MetadataValue
        MetadataValueDTO metadataValueDTO = metadataValueMapper.toDto(metadataValue);

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

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

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

        // Create the MetadataValue
        MetadataValueDTO metadataValueDTO = metadataValueMapper.toDto(metadataValue);

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

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

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

        // Create the MetadataValue
        MetadataValueDTO metadataValueDTO = metadataValueMapper.toDto(metadataValue);

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

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

    @Test
    @Transactional
    void partialUpdateMetadataValueWithPatch() throws Exception {
        // Initialize the database
        insertedMetadataValue = metadataValueRepository.saveAndFlush(metadataValue);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the metadataValue using partial update
        MetadataValue partialUpdatedMetadataValue = new MetadataValue();
        partialUpdatedMetadataValue.setId(metadataValue.getId());

        partialUpdatedMetadataValue.targetDomainId(UPDATED_TARGET_DOMAIN_ID).value(UPDATED_VALUE);

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

        // Validate the MetadataValue in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertMetadataValueUpdatableFieldsEquals(
            createUpdateProxyForBean(partialUpdatedMetadataValue, metadataValue),
            getPersistedMetadataValue(metadataValue)
        );
    }

    @Test
    @Transactional
    void fullUpdateMetadataValueWithPatch() throws Exception {
        // Initialize the database
        insertedMetadataValue = metadataValueRepository.saveAndFlush(metadataValue);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the metadataValue using partial update
        MetadataValue partialUpdatedMetadataValue = new MetadataValue();
        partialUpdatedMetadataValue.setId(metadataValue.getId());

        partialUpdatedMetadataValue
            .metadataPropertyCode(UPDATED_METADATA_PROPERTY_CODE)
            .targetDomainKey(UPDATED_TARGET_DOMAIN_KEY)
            .targetDomainId(UPDATED_TARGET_DOMAIN_ID)
            .value(UPDATED_VALUE)
            .version(UPDATED_VERSION);

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

        // Validate the MetadataValue in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertMetadataValueUpdatableFieldsEquals(partialUpdatedMetadataValue, getPersistedMetadataValue(partialUpdatedMetadataValue));
    }

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

        // Create the MetadataValue
        MetadataValueDTO metadataValueDTO = metadataValueMapper.toDto(metadataValue);

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

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

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

        // Create the MetadataValue
        MetadataValueDTO metadataValueDTO = metadataValueMapper.toDto(metadataValue);

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

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

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

        // Create the MetadataValue
        MetadataValueDTO metadataValueDTO = metadataValueMapper.toDto(metadataValue);

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

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

    @Test
    @Transactional
    void deleteMetadataValue() throws Exception {
        // Initialize the database
        insertedMetadataValue = metadataValueRepository.saveAndFlush(metadataValue);

        long databaseSizeBeforeDelete = getRepositoryCount();

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

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

    protected long getRepositoryCount() {
        return metadataValueRepository.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 MetadataValue getPersistedMetadataValue(MetadataValue metadataValue) {
        return metadataValueRepository.findById(metadataValue.getId()).orElseThrow();
    }

    protected void assertPersistedMetadataValueToMatchAllProperties(MetadataValue expectedMetadataValue) {
        assertMetadataValueAllPropertiesEquals(expectedMetadataValue, getPersistedMetadataValue(expectedMetadataValue));
    }

    protected void assertPersistedMetadataValueToMatchUpdatableProperties(MetadataValue expectedMetadataValue) {
        assertMetadataValueAllUpdatablePropertiesEquals(expectedMetadataValue, getPersistedMetadataValue(expectedMetadataValue));
    }
}
