package it.sw.pa.comune.artegna.web.rest;

import static it.sw.pa.comune.artegna.domain.LiberatoriaAsserts.*;
import static it.sw.pa.comune.artegna.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 it.sw.pa.comune.artegna.IntegrationTest;
import it.sw.pa.comune.artegna.domain.Liberatoria;
import it.sw.pa.comune.artegna.repository.LiberatoriaRepository;
import it.sw.pa.comune.artegna.service.LiberatoriaService;
import it.sw.pa.comune.artegna.service.dto.LiberatoriaDTO;
import it.sw.pa.comune.artegna.service.mapper.LiberatoriaMapper;
import jakarta.persistence.EntityManager;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
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 LiberatoriaResource} REST controller.
 */
@IntegrationTest
@ExtendWith(MockitoExtension.class)
@AutoConfigureMockMvc
@WithMockUser
class LiberatoriaResourceIT {

    private static final Instant DEFAULT_ACCETTATA = Instant.ofEpochMilli(0L);
    private static final Instant UPDATED_ACCETTATA = Instant.now().truncatedTo(ChronoUnit.MILLIS);

    private static final String ENTITY_API_URL = "/api/liberatorias";
    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() + (2L * Integer.MAX_VALUE));

    @Autowired
    private ObjectMapper om;

    @Autowired
    private LiberatoriaRepository liberatoriaRepository;

    @Mock
    private LiberatoriaRepository liberatoriaRepositoryMock;

    @Autowired
    private LiberatoriaMapper liberatoriaMapper;

    @Mock
    private LiberatoriaService liberatoriaServiceMock;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restLiberatoriaMockMvc;

    private Liberatoria liberatoria;

    private Liberatoria insertedLiberatoria;

    /**
     * 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 Liberatoria createEntity() {
        return new Liberatoria().accettata(DEFAULT_ACCETTATA);
    }

    /**
     * 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 Liberatoria createUpdatedEntity() {
        return new Liberatoria().accettata(UPDATED_ACCETTATA);
    }

    @BeforeEach
    void initTest() {
        liberatoria = createEntity();
    }

    @AfterEach
    void cleanup() {
        if (insertedLiberatoria != null) {
            liberatoriaRepository.delete(insertedLiberatoria);
            insertedLiberatoria = null;
        }
    }

    @Test
    @Transactional
    void createLiberatoria() throws Exception {
        long databaseSizeBeforeCreate = getRepositoryCount();
        // Create the Liberatoria
        LiberatoriaDTO liberatoriaDTO = liberatoriaMapper.toDto(liberatoria);
        var returnedLiberatoriaDTO = om.readValue(
            restLiberatoriaMockMvc
                .perform(
                    post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(liberatoriaDTO))
                )
                .andExpect(status().isCreated())
                .andReturn()
                .getResponse()
                .getContentAsString(),
            LiberatoriaDTO.class
        );

        // Validate the Liberatoria in the database
        assertIncrementedRepositoryCount(databaseSizeBeforeCreate);
        var returnedLiberatoria = liberatoriaMapper.toEntity(returnedLiberatoriaDTO);
        assertLiberatoriaUpdatableFieldsEquals(returnedLiberatoria, getPersistedLiberatoria(returnedLiberatoria));

        insertedLiberatoria = returnedLiberatoria;
    }

    @Test
    @Transactional
    void createLiberatoriaWithExistingId() throws Exception {
        // Create the Liberatoria with an existing ID
        liberatoria.setId(1L);
        LiberatoriaDTO liberatoriaDTO = liberatoriaMapper.toDto(liberatoria);

        long databaseSizeBeforeCreate = getRepositoryCount();

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

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

    @Test
    @Transactional
    void getAllLiberatorias() throws Exception {
        // Initialize the database
        insertedLiberatoria = liberatoriaRepository.saveAndFlush(liberatoria);

        // Get all the liberatoriaList
        restLiberatoriaMockMvc
            .perform(get(ENTITY_API_URL + "?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(liberatoria.getId().intValue())))
            .andExpect(jsonPath("$.[*].accettata").value(hasItem(DEFAULT_ACCETTATA.toString())));
    }

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

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

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

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

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

    @Test
    @Transactional
    void getLiberatoria() throws Exception {
        // Initialize the database
        insertedLiberatoria = liberatoriaRepository.saveAndFlush(liberatoria);

        // Get the liberatoria
        restLiberatoriaMockMvc
            .perform(get(ENTITY_API_URL_ID, liberatoria.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.id").value(liberatoria.getId().intValue()))
            .andExpect(jsonPath("$.accettata").value(DEFAULT_ACCETTATA.toString()));
    }

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

    @Test
    @Transactional
    void putExistingLiberatoria() throws Exception {
        // Initialize the database
        insertedLiberatoria = liberatoriaRepository.saveAndFlush(liberatoria);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the liberatoria
        Liberatoria updatedLiberatoria = liberatoriaRepository.findById(liberatoria.getId()).orElseThrow();
        // Disconnect from session so that the updates on updatedLiberatoria are not directly saved in db
        em.detach(updatedLiberatoria);
        updatedLiberatoria.accettata(UPDATED_ACCETTATA);
        LiberatoriaDTO liberatoriaDTO = liberatoriaMapper.toDto(updatedLiberatoria);

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

        // Validate the Liberatoria in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertPersistedLiberatoriaToMatchAllProperties(updatedLiberatoria);
    }

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

        // Create the Liberatoria
        LiberatoriaDTO liberatoriaDTO = liberatoriaMapper.toDto(liberatoria);

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

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

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

        // Create the Liberatoria
        LiberatoriaDTO liberatoriaDTO = liberatoriaMapper.toDto(liberatoria);

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

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

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

        // Create the Liberatoria
        LiberatoriaDTO liberatoriaDTO = liberatoriaMapper.toDto(liberatoria);

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

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

    @Test
    @Transactional
    void partialUpdateLiberatoriaWithPatch() throws Exception {
        // Initialize the database
        insertedLiberatoria = liberatoriaRepository.saveAndFlush(liberatoria);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the liberatoria using partial update
        Liberatoria partialUpdatedLiberatoria = new Liberatoria();
        partialUpdatedLiberatoria.setId(liberatoria.getId());

        partialUpdatedLiberatoria.accettata(UPDATED_ACCETTATA);

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

        // Validate the Liberatoria in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertLiberatoriaUpdatableFieldsEquals(
            createUpdateProxyForBean(partialUpdatedLiberatoria, liberatoria),
            getPersistedLiberatoria(liberatoria)
        );
    }

    @Test
    @Transactional
    void fullUpdateLiberatoriaWithPatch() throws Exception {
        // Initialize the database
        insertedLiberatoria = liberatoriaRepository.saveAndFlush(liberatoria);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the liberatoria using partial update
        Liberatoria partialUpdatedLiberatoria = new Liberatoria();
        partialUpdatedLiberatoria.setId(liberatoria.getId());

        partialUpdatedLiberatoria.accettata(UPDATED_ACCETTATA);

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

        // Validate the Liberatoria in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertLiberatoriaUpdatableFieldsEquals(partialUpdatedLiberatoria, getPersistedLiberatoria(partialUpdatedLiberatoria));
    }

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

        // Create the Liberatoria
        LiberatoriaDTO liberatoriaDTO = liberatoriaMapper.toDto(liberatoria);

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

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

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

        // Create the Liberatoria
        LiberatoriaDTO liberatoriaDTO = liberatoriaMapper.toDto(liberatoria);

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

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

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

        // Create the Liberatoria
        LiberatoriaDTO liberatoriaDTO = liberatoriaMapper.toDto(liberatoria);

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

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

    @Test
    @Transactional
    void deleteLiberatoria() throws Exception {
        // Initialize the database
        insertedLiberatoria = liberatoriaRepository.saveAndFlush(liberatoria);

        long databaseSizeBeforeDelete = getRepositoryCount();

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

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

    protected long getRepositoryCount() {
        return liberatoriaRepository.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 Liberatoria getPersistedLiberatoria(Liberatoria liberatoria) {
        return liberatoriaRepository.findById(liberatoria.getId()).orElseThrow();
    }

    protected void assertPersistedLiberatoriaToMatchAllProperties(Liberatoria expectedLiberatoria) {
        assertLiberatoriaAllPropertiesEquals(expectedLiberatoria, getPersistedLiberatoria(expectedLiberatoria));
    }

    protected void assertPersistedLiberatoriaToMatchUpdatableProperties(Liberatoria expectedLiberatoria) {
        assertLiberatoriaAllUpdatablePropertiesEquals(expectedLiberatoria, getPersistedLiberatoria(expectedLiberatoria));
    }
}
