package de.thpeetz.kontor.bookshelf.data;

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

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 de.thpeetz.kontor.bookshelf.TestConstants;

@SpringBootTest
class BookshelfPublisherTest {

    @Autowired
    private BookshelfPublisherRepository publisherRepository;

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

    @Test
    void throwExceptionWhenPublisherSavedWithEmptyName() {
        BookshelfPublisher publisher = new BookshelfPublisher();
        assertThrows(TransactionSystemException.class, () -> {
            publisherRepository.save(publisher);
        });
    }

    @Test
    void savePublisherWithIdenticalName() {
        BookshelfPublisher publisher1 = new BookshelfPublisher();
        publisher1.setName(TestConstants.PUBLISHER_NAME);
        publisherRepository.save(publisher1);
        BookshelfPublisher publisher2 = new BookshelfPublisher();
        publisher2.setName(TestConstants.PUBLISHER_NAME);
        assertThrows(DataIntegrityViolationException.class, () -> {
            publisherRepository.save(publisher2);
        });
        publisherRepository.delete(publisher1);
        assertEquals(TestConstants.PUBLISHER_COUNT, publisherRepository.findAll().size());
    }
}
