package de.thpeetz.kontor.bookshelf.data;

import de.thpeetz.kontor.bookshelf.TestConstants;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.transaction.TransactionSystemException;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

@SpringBootTest
class ArticleTest {

    @Autowired
    ArticleRepository articleRepository;

    @Test
    void checkInitialLoad() {
        assertEquals(TestConstants.BOOK_COUNT, articleRepository.findAll().size());
    }

    @Test
    void exceptionThrownWhenSavingEmptyFields() {
        Article article = new Article();
        assertThrows(TransactionSystemException.class, () -> {
            articleRepository.save(article);
        });
    }

    @Test
    void exceptionThrownWhenSavingIdenticalTitle() {
        Article article = new Article();
        article.setTitle(TestConstants.ARTICLE_TITLE);
        Article savedArticle = articleRepository.save(article);
        Article article1 = new Article();
        article1.setTitle(article.getTitle());
        assertThrows(DataIntegrityViolationException.class, ()-> {
            articleRepository.save(article1);
        });
        articleRepository.delete(savedArticle);
        assertEquals(TestConstants.ARTICLE_COUNT, articleRepository.findAll().size());
    }
}