package de.thpeetz.kontor.bookshelf.data;

import de.thpeetz.kontor.bookshelf.TestConstants;
import de.thpeetz.kontor.comics.data.Publisher;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.transaction.TransactionSystemException;

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

@SpringBootTest
class BookTest {

    @Autowired
    BookRepository bookRepository;

    @Autowired
    BookshelfPublisherRepository bookshelfPublisherRepository;

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

    @Test
    void exceptionThrownWhenSavingEmptyFields() {
        Book book = new Book();
        assertThrows(TransactionSystemException.class, () -> {
            bookRepository.save(book);
        });
    }

    @Test
    void exceptionThrownWhenSavingIdenticalISBN() {
        BookshelfPublisher publisher = new BookshelfPublisher();
        publisher.setName(TestConstants.PUBLISHER_NAME);
        BookshelfPublisher savedPublisher = bookshelfPublisherRepository.save(publisher);
        Book book = new Book();
        book.setTitle(TestConstants.BOOK_TITLE);
        book.setIsbn(TestConstants.BOOK_ISBN);
        book.setPublisher(savedPublisher);
        Book savedBook = bookRepository.save(book);
        Book book1 = new Book();
        book1.setTitle(book.getTitle());
        book1.setIsbn(book.getIsbn());
        assertThrows(TransactionSystemException.class, ()-> {
            bookRepository.save(book1);
        });
        bookRepository.delete(book);
        assertEquals(TestConstants.BOOK_COUNT, bookRepository.findAll().size());
        bookshelfPublisherRepository.delete(savedPublisher);
        assertEquals(TestConstants.PUBLISHER_COUNT, bookshelfPublisherRepository.findAll().size());
    }
}
