package de.thpeetz.kontor.bookshelf.data;

import de.thpeetz.kontor.bookshelf.TestConstants;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

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

@SpringBootTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@Disabled
class ArticleAuthorRepositoryTest {

    @Autowired
    ArticleAuthorRepository articleAuthorRepository;

    @Autowired
    AuthorRepository authorRepository;

    @Autowired
    ArticleRepository articleRepository;

    @Test
    @Order(1)
    void saveArticleAuthor() {
        Author author = new Author();
        author.setFirstName(TestConstants.AUTHOR_FIRSTNAME);
        author.setLastName(TestConstants.AUTHOR_LASTNAME);
        Author savedAuthor = authorRepository.save(author);
        assertEquals(TestConstants.AUTHOR_COUNT+1, authorRepository.findAll().size());
        Article article = new Article();
        article.setTitle(TestConstants.ARTICLE_TITLE);
        Article savedArticle = articleRepository.save(article);
        ArticleAuthor articleAuthor = new ArticleAuthor();
        articleAuthor.setArticle(article);
        articleAuthor.setAuthor(author);
        ArticleAuthor savedArticleAuthor = articleAuthorRepository.save(articleAuthor);
        assertEquals(TestConstants.ARTICLEAUTHOR_COUNT+1, articleAuthorRepository.findAll().size());
    }

    @Test
    @Order(2)
    void testFindByArticle() {
        Article article = articleRepository.findByTitle(TestConstants.ARTICLE_TITLE).get(0);
        assertEquals(1, articleAuthorRepository.findByArticle(article).size());
    }

    @Test
    @Order(3)
    void testFindByAuthor() {
        Author author = authorRepository.findByFirstNameAndLastName(TestConstants.AUTHOR_FIRSTNAME, TestConstants.AUTHOR_LASTNAME);
        assertEquals(1, articleAuthorRepository.findByAuthor(author).size());
    }

    @Test
    @Order(4)
    void deleteArticleAuthor() {
        assertEquals(1, articleAuthorRepository.findAll().size());
        ArticleAuthor articleAuthor = articleAuthorRepository.findAll().get(0);
        Author author = articleAuthor.getAuthor();
        author.getArticleAuthors().remove(articleAuthor);
        author = authorRepository.save(author);
        Article article = articleAuthor.getArticle();
        article.getAuthors().remove(articleAuthor);
        article = articleRepository.save(article);
        articleAuthorRepository.delete(articleAuthor);
        assertEquals(TestConstants.ARTICLEAUTHOR_COUNT, articleAuthorRepository.findAll().size());
        authorRepository.delete(author);
        assertEquals(TestConstants.AUTHOR_COUNT, authorRepository.findAll().size());
        articleRepository.delete(article);
        assertEquals(TestConstants.ARTICLE_COUNT, articleRepository.findAll().size());
    }
}
