package de.thpeetz.kontor.comics.data;

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

import java.util.List;

import de.thpeetz.kontor.comics.repository.*;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
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.comics.TestConstants;
import de.thpeetz.kontor.comics.services.ComicService;

@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class ComicTest {

    @Autowired
    private ComicRepository comicRepository;

    @Autowired
    private ComicService comicService;

    @Test
    @Order(1)
    void checkInitialDataLoad() {
        List<Comic> comics = comicRepository.findAll();
        assertEquals(TestConstants.COMIC_COUNT, comics.size());
    }

    @Test
    @Order(2)
    void exceptionThrownWhenSavingComicWithoutPublisher() {
        Comic comic = new Comic();
        comic.setTitle(TestConstants.COMIC_TITLE);
        assertThrows(TransactionSystemException.class, () -> {
            comicRepository.save(comic);
        });
    }

    @Test
    @Order(3)
    void exceptionThrownWhenSavingComicWithEmptyTitle() {
        Comic comic = new Comic();
        Publisher publisher = TestConstants.getPublisherForComicTests(comicService);
        comic.setPublisher(publisher);
        assertNull(comic.getTitle());
        assertThrows(TransactionSystemException.class, () -> {
            comicRepository.save(comic);
        });
        comic.setTitle("");
        assertTrue(comic.getTitle().isEmpty());
        assertThrows(TransactionSystemException.class, () -> {
            comicRepository.save(comic);
        });
    }

    @Test
    @Order(4)
    void exceptionThrownWhenSavingComicWithSameNameFromDifferentPublishers() {
        Publisher publisher = TestConstants.getPublisherForComicTests(comicService);
        Comic comic = new Comic();
        comic.setTitle(TestConstants.SOJOURN_TPB_COMIC_TITLE);
        comic.setPublisher(publisher);
        assertThrows(DataIntegrityViolationException.class, () -> {
            comicRepository.save(comic);
        });
    }
}
