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

import static it.sw.pa.comune.artegna.domain.ModelloLiberatoriaAsserts.*;
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.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.ModelloLiberatoria;
import it.sw.pa.comune.artegna.repository.ModelloLiberatoriaRepository;
import it.sw.pa.comune.artegna.service.dto.ModelloLiberatoriaDTO;
import it.sw.pa.comune.artegna.service.mapper.ModelloLiberatoriaMapper;
import jakarta.persistence.EntityManager;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Base64;
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 ModelloLiberatoriaResource} REST controller.
 */
@IntegrationTest
@AutoConfigureMockMvc
@WithMockUser
class ModelloLiberatoriaResourceIT {

    private static final String DEFAULT_NOME = "AAAAAAAAAA";
    private static final String UPDATED_NOME = "BBBBBBBBBB";

    private static final String DEFAULT_TESTO = "AAAAAAAAAA";
    private static final String UPDATED_TESTO = "BBBBBBBBBB";

    private static final byte[] DEFAULT_DOCUMENTO = TestUtil.createByteArray(1, "0");
    private static final byte[] UPDATED_DOCUMENTO = TestUtil.createByteArray(1, "1");
    private static final String DEFAULT_DOCUMENTO_CONTENT_TYPE = "image/jpg";
    private static final String UPDATED_DOCUMENTO_CONTENT_TYPE = "image/png";

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

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

    private static final String ENTITY_API_URL = "/api/modello-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 ModelloLiberatoriaRepository modelloLiberatoriaRepository;

    @Autowired
    private ModelloLiberatoriaMapper modelloLiberatoriaMapper;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restModelloLiberatoriaMockMvc;

    private ModelloLiberatoria modelloLiberatoria;

    private ModelloLiberatoria insertedModelloLiberatoria;

    /**
     * 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 ModelloLiberatoria createEntity() {
        return new ModelloLiberatoria()
            .nome(DEFAULT_NOME)
            .testo(DEFAULT_TESTO)
            .documento(DEFAULT_DOCUMENTO)
            .documentoContentType(DEFAULT_DOCUMENTO_CONTENT_TYPE)
            .validoDal(DEFAULT_VALIDO_DAL)
            .validoAl(DEFAULT_VALIDO_AL);
    }

    /**
     * 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 ModelloLiberatoria createUpdatedEntity() {
        return new ModelloLiberatoria()
            .nome(UPDATED_NOME)
            .testo(UPDATED_TESTO)
            .documento(UPDATED_DOCUMENTO)
            .documentoContentType(UPDATED_DOCUMENTO_CONTENT_TYPE)
            .validoDal(UPDATED_VALIDO_DAL)
            .validoAl(UPDATED_VALIDO_AL);
    }

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

    @AfterEach
    void cleanup() {
        if (insertedModelloLiberatoria != null) {
            modelloLiberatoriaRepository.delete(insertedModelloLiberatoria);
            insertedModelloLiberatoria = null;
        }
    }

    @Test
    @Transactional
    void createModelloLiberatoria() throws Exception {
        long databaseSizeBeforeCreate = getRepositoryCount();
        // Create the ModelloLiberatoria
        ModelloLiberatoriaDTO modelloLiberatoriaDTO = modelloLiberatoriaMapper.toDto(modelloLiberatoria);
        var returnedModelloLiberatoriaDTO = om.readValue(
            restModelloLiberatoriaMockMvc
                .perform(
                    post(ENTITY_API_URL)
                        .with(csrf())
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(om.writeValueAsBytes(modelloLiberatoriaDTO))
                )
                .andExpect(status().isCreated())
                .andReturn()
                .getResponse()
                .getContentAsString(),
            ModelloLiberatoriaDTO.class
        );

        // Validate the ModelloLiberatoria in the database
        assertIncrementedRepositoryCount(databaseSizeBeforeCreate);
        var returnedModelloLiberatoria = modelloLiberatoriaMapper.toEntity(returnedModelloLiberatoriaDTO);
        assertModelloLiberatoriaUpdatableFieldsEquals(
            returnedModelloLiberatoria,
            getPersistedModelloLiberatoria(returnedModelloLiberatoria)
        );

        insertedModelloLiberatoria = returnedModelloLiberatoria;
    }

    @Test
    @Transactional
    void createModelloLiberatoriaWithExistingId() throws Exception {
        // Create the ModelloLiberatoria with an existing ID
        modelloLiberatoria.setId(1L);
        ModelloLiberatoriaDTO modelloLiberatoriaDTO = modelloLiberatoriaMapper.toDto(modelloLiberatoria);

        long databaseSizeBeforeCreate = getRepositoryCount();

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

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

    @Test
    @Transactional
    void getAllModelloLiberatorias() throws Exception {
        // Initialize the database
        insertedModelloLiberatoria = modelloLiberatoriaRepository.saveAndFlush(modelloLiberatoria);

        // Get all the modelloLiberatoriaList
        restModelloLiberatoriaMockMvc
            .perform(get(ENTITY_API_URL + "?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(modelloLiberatoria.getId().intValue())))
            .andExpect(jsonPath("$.[*].nome").value(hasItem(DEFAULT_NOME)))
            .andExpect(jsonPath("$.[*].testo").value(hasItem(DEFAULT_TESTO)))
            .andExpect(jsonPath("$.[*].documentoContentType").value(hasItem(DEFAULT_DOCUMENTO_CONTENT_TYPE)))
            .andExpect(jsonPath("$.[*].documento").value(hasItem(Base64.getEncoder().encodeToString(DEFAULT_DOCUMENTO))))
            .andExpect(jsonPath("$.[*].validoDal").value(hasItem(DEFAULT_VALIDO_DAL.toString())))
            .andExpect(jsonPath("$.[*].validoAl").value(hasItem(DEFAULT_VALIDO_AL.toString())));
    }

    @Test
    @Transactional
    void getModelloLiberatoria() throws Exception {
        // Initialize the database
        insertedModelloLiberatoria = modelloLiberatoriaRepository.saveAndFlush(modelloLiberatoria);

        // Get the modelloLiberatoria
        restModelloLiberatoriaMockMvc
            .perform(get(ENTITY_API_URL_ID, modelloLiberatoria.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.id").value(modelloLiberatoria.getId().intValue()))
            .andExpect(jsonPath("$.nome").value(DEFAULT_NOME))
            .andExpect(jsonPath("$.testo").value(DEFAULT_TESTO))
            .andExpect(jsonPath("$.documentoContentType").value(DEFAULT_DOCUMENTO_CONTENT_TYPE))
            .andExpect(jsonPath("$.documento").value(Base64.getEncoder().encodeToString(DEFAULT_DOCUMENTO)))
            .andExpect(jsonPath("$.validoDal").value(DEFAULT_VALIDO_DAL.toString()))
            .andExpect(jsonPath("$.validoAl").value(DEFAULT_VALIDO_AL.toString()));
    }

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

    @Test
    @Transactional
    void putExistingModelloLiberatoria() throws Exception {
        // Initialize the database
        insertedModelloLiberatoria = modelloLiberatoriaRepository.saveAndFlush(modelloLiberatoria);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the modelloLiberatoria
        ModelloLiberatoria updatedModelloLiberatoria = modelloLiberatoriaRepository.findById(modelloLiberatoria.getId()).orElseThrow();
        // Disconnect from session so that the updates on updatedModelloLiberatoria are not directly saved in db
        em.detach(updatedModelloLiberatoria);
        updatedModelloLiberatoria
            .nome(UPDATED_NOME)
            .testo(UPDATED_TESTO)
            .documento(UPDATED_DOCUMENTO)
            .documentoContentType(UPDATED_DOCUMENTO_CONTENT_TYPE)
            .validoDal(UPDATED_VALIDO_DAL)
            .validoAl(UPDATED_VALIDO_AL);
        ModelloLiberatoriaDTO modelloLiberatoriaDTO = modelloLiberatoriaMapper.toDto(updatedModelloLiberatoria);

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

        // Validate the ModelloLiberatoria in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertPersistedModelloLiberatoriaToMatchAllProperties(updatedModelloLiberatoria);
    }

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

        // Create the ModelloLiberatoria
        ModelloLiberatoriaDTO modelloLiberatoriaDTO = modelloLiberatoriaMapper.toDto(modelloLiberatoria);

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

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

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

        // Create the ModelloLiberatoria
        ModelloLiberatoriaDTO modelloLiberatoriaDTO = modelloLiberatoriaMapper.toDto(modelloLiberatoria);

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

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

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

        // Create the ModelloLiberatoria
        ModelloLiberatoriaDTO modelloLiberatoriaDTO = modelloLiberatoriaMapper.toDto(modelloLiberatoria);

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

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

    @Test
    @Transactional
    void partialUpdateModelloLiberatoriaWithPatch() throws Exception {
        // Initialize the database
        insertedModelloLiberatoria = modelloLiberatoriaRepository.saveAndFlush(modelloLiberatoria);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the modelloLiberatoria using partial update
        ModelloLiberatoria partialUpdatedModelloLiberatoria = new ModelloLiberatoria();
        partialUpdatedModelloLiberatoria.setId(modelloLiberatoria.getId());

        partialUpdatedModelloLiberatoria.testo(UPDATED_TESTO).validoDal(UPDATED_VALIDO_DAL);

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

        // Validate the ModelloLiberatoria in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertModelloLiberatoriaUpdatableFieldsEquals(
            createUpdateProxyForBean(partialUpdatedModelloLiberatoria, modelloLiberatoria),
            getPersistedModelloLiberatoria(modelloLiberatoria)
        );
    }

    @Test
    @Transactional
    void fullUpdateModelloLiberatoriaWithPatch() throws Exception {
        // Initialize the database
        insertedModelloLiberatoria = modelloLiberatoriaRepository.saveAndFlush(modelloLiberatoria);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the modelloLiberatoria using partial update
        ModelloLiberatoria partialUpdatedModelloLiberatoria = new ModelloLiberatoria();
        partialUpdatedModelloLiberatoria.setId(modelloLiberatoria.getId());

        partialUpdatedModelloLiberatoria
            .nome(UPDATED_NOME)
            .testo(UPDATED_TESTO)
            .documento(UPDATED_DOCUMENTO)
            .documentoContentType(UPDATED_DOCUMENTO_CONTENT_TYPE)
            .validoDal(UPDATED_VALIDO_DAL)
            .validoAl(UPDATED_VALIDO_AL);

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

        // Validate the ModelloLiberatoria in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertModelloLiberatoriaUpdatableFieldsEquals(
            partialUpdatedModelloLiberatoria,
            getPersistedModelloLiberatoria(partialUpdatedModelloLiberatoria)
        );
    }

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

        // Create the ModelloLiberatoria
        ModelloLiberatoriaDTO modelloLiberatoriaDTO = modelloLiberatoriaMapper.toDto(modelloLiberatoria);

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

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

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

        // Create the ModelloLiberatoria
        ModelloLiberatoriaDTO modelloLiberatoriaDTO = modelloLiberatoriaMapper.toDto(modelloLiberatoria);

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

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

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

        // Create the ModelloLiberatoria
        ModelloLiberatoriaDTO modelloLiberatoriaDTO = modelloLiberatoriaMapper.toDto(modelloLiberatoria);

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

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

    @Test
    @Transactional
    void deleteModelloLiberatoria() throws Exception {
        // Initialize the database
        insertedModelloLiberatoria = modelloLiberatoriaRepository.saveAndFlush(modelloLiberatoria);

        long databaseSizeBeforeDelete = getRepositoryCount();

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

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

    protected long getRepositoryCount() {
        return modelloLiberatoriaRepository.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 ModelloLiberatoria getPersistedModelloLiberatoria(ModelloLiberatoria modelloLiberatoria) {
        return modelloLiberatoriaRepository.findById(modelloLiberatoria.getId()).orElseThrow();
    }

    protected void assertPersistedModelloLiberatoriaToMatchAllProperties(ModelloLiberatoria expectedModelloLiberatoria) {
        assertModelloLiberatoriaAllPropertiesEquals(expectedModelloLiberatoria, getPersistedModelloLiberatoria(expectedModelloLiberatoria));
    }

    protected void assertPersistedModelloLiberatoriaToMatchUpdatableProperties(ModelloLiberatoria expectedModelloLiberatoria) {
        assertModelloLiberatoriaAllUpdatablePropertiesEquals(
            expectedModelloLiberatoria,
            getPersistedModelloLiberatoria(expectedModelloLiberatoria)
        );
    }
}
