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.*;

@SpringBootTest
class AuthorTest {

    @Autowired
    private AuthorRepository authorRepository;

    @Test
    void throwExceptionWhenPlayerSavedWithEmptyName() {
        Author author = new Author();
        assertThrows(TransactionSystemException.class, () -> {
            authorRepository.save(author);
        });
    }

    @Test
    void throwExceptionWhenPlayerSavedWithExistingName() {
        assertEquals(TestConstants.AUTHOR_COUNT, authorRepository.findAll().size());
        Author existingAuthor = new Author();
        existingAuthor.setFirstName(TestConstants.AUTHOR_FIRSTNAME);
        existingAuthor.setLastName(TestConstants.AUTHOR_LASTNAME);
        existingAuthor = authorRepository.save(existingAuthor);
        assertEquals(TestConstants.AUTHOR_COUNT+1, authorRepository.findAll().size());
        Author author = new Author();
        author.setFirstName(existingAuthor.getFirstName());
        author.setLastName(existingAuthor.getLastName());
        assertThrows(DataIntegrityViolationException.class, () -> {
            authorRepository.save(author);
        });
        assertNotNull(existingAuthor);
        authorRepository.delete(existingAuthor);
        assertEquals(TestConstants.AUTHOR_COUNT, authorRepository.findAll().size());
    }
}
