package com.iqser.red.service.peristence.v1.server.integration.tests;

import static org.assertj.core.api.Assertions.assertThat;

import java.time.OffsetDateTime;
import java.time.temporal.ChronoUnit;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.iqser.red.service.peristence.v1.server.integration.client.IndexInformationClient;
import com.iqser.red.service.peristence.v1.server.integration.utils.AbstractPersistenceServerServiceTest;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.repository.IndexInformationRepository;
import com.iqser.red.service.persistence.service.v1.api.shared.model.index.IndexInformation;

import feign.FeignException;

public class IndexInformationTest extends AbstractPersistenceServerServiceTest {

    @Autowired
    private IndexInformationClient indexInformationClient;

    @Autowired
    private IndexInformationRepository indexInformationRepository;


    @Test
    public void test() {

        // No indexInformation exist
        try {
            IndexInformation indexInformation = indexInformationClient.getIndexInformation();
        } catch (FeignException e) {
            assertThat(e.status()).isEqualTo(404);
        }

        // Save indexInformation the first time
        String hash = "This is the hash from the search-service";
        OffsetDateTime timeStamp = OffsetDateTime.now().truncatedTo(ChronoUnit.MILLIS);

        IndexInformation indexInformation = IndexInformation.builder().indexConfigurationHash(hash).updateDate(timeStamp).build();
        indexInformationClient.updateIndexInformation(indexInformation);

        IndexInformation indexInformationFromDb = indexInformationClient.getIndexInformation();
        assertThat(indexInformationFromDb).isNotNull();
        assertThat(indexInformationFromDb.getIndexConfigurationHash()).isEqualTo(hash);
        assertThat(indexInformationFromDb.getUpdateDate()).isEqualTo(timeStamp);

        // Update indexInformation
        String newHash = "This is 2. the hash from the search-service";
        OffsetDateTime newTimeStamp = OffsetDateTime.now().truncatedTo(ChronoUnit.MILLIS);

        IndexInformation newIndexInformation = IndexInformation.builder().indexConfigurationHash(newHash).updateDate(newTimeStamp).build();
        indexInformationClient.updateIndexInformation(newIndexInformation);

        indexInformationFromDb = indexInformationClient.getIndexInformation();
        assertThat(indexInformationFromDb).isNotNull();
        assertThat(indexInformationFromDb.getIndexConfigurationHash()).isEqualTo(newHash);
        assertThat(indexInformationFromDb.getUpdateDate()).isEqualTo(newTimeStamp);
    }

}
