package de.thpeetz.kontor.bookshelf.data;

import static org.junit.jupiter.api.Assertions.*;

import java.util.List;

import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import de.thpeetz.kontor.bookshelf.TestConstants;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class BookshelfPublisherRepositoryTest {

    @Autowired
    private BookshelfPublisherRepository publisherRepository;

    @Test
    @Order(1)
    void checkInitialLoad() {
        assertEquals(TestConstants.PUBLISHER_COUNT, publisherRepository.findAll().size());
    }

    @Test
    @Order(2)
    void savePublisher() {
        BookshelfPublisher publisher = new BookshelfPublisher();
        publisher.setName(TestConstants.PUBLISHER_NAME);
        publisherRepository.save(publisher);
        assertEquals(TestConstants.PUBLISHER_COUNT + 1, publisherRepository.findAll().size());
    }

    @Test
    @Order(3)
    void findPublisherByName() {
        assertEquals(TestConstants.PUBLISHER_COUNT + 1, publisherRepository.findAll().size());
        log.info("Liste der Publisher: {}", publisherRepository.findAll());
        BookshelfPublisher publisher = publisherRepository.findByName(TestConstants.PUBLISHER_NAME);
        assertNotNull(publisher);
        assertEquals(TestConstants.PUBLISHER_NAME, publisher.getName());
        BookshelfPublisher notFound = publisherRepository.findByName(TestConstants.PUBLISHER_SEARCH);
        assertNull(notFound);
        List<BookshelfPublisher> publishers = publisherRepository
                .findByNameIgnoreCase(TestConstants.PUBLISHER_NAME.toLowerCase());
        assertEquals(1, publishers.size());
        assertEquals(TestConstants.PUBLISHER_NAME, publishers.get(0).getName());
    }

    @Test
    @Order(4)
    void searchPublisher() {
        List<BookshelfPublisher> publishers = publisherRepository.search(TestConstants.PUBLISHER_NAME.substring(2, 6));
        assertEquals(1, publishers.size());
        assertEquals(TestConstants.PUBLISHER_NAME, publishers.get(0).getName());
    }

    @Test
    @Order(5)
    void deletePublisher() {
        BookshelfPublisher publisher = publisherRepository.findByName(TestConstants.PUBLISHER_NAME);
        assertNotNull(publisher);
        publisherRepository.delete(publisher);
        assertEquals(TestConstants.PUBLISHER_COUNT, publisherRepository.findAll().size());
    }
}
