package de.thpeetz.kontor.comics.data;

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

import de.thpeetz.kontor.comics.repository.*;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.TransactionSystemException;

import de.thpeetz.kontor.comics.TestConstants;
import de.thpeetz.kontor.comics.services.ComicService;

@SpringBootTest
class TradePaperbackTest {

    @Autowired
    private TradePaperbackRepository tradePaperbackRepository;

    @Autowired
    private ComicService comicService;

    @Test
    void checkInitialDataLoad() {
        assertEquals(TestConstants.TRADEPAPERBACK_COUNT, tradePaperbackRepository.findAll().size());
    }

    @Test
    void exceptionThrownWhenSavingTradePaperbackWithEmptyName() {
        Comic comic = TestConstants.getComicWithoutReferences(comicService);
        assertNotNull(comic);
        TradePaperback tradePaperback = new TradePaperback();
        tradePaperback.setComic(comic);
        assertThrows(TransactionSystemException.class, () -> {
            tradePaperbackRepository.save(tradePaperback);
        });
    }

    @Test
    void exceptionThrownWhenSavingTradePaperbackWithoutComic() {
        TradePaperback tradePaperback = new TradePaperback();
        tradePaperback.setName(TestConstants.TRADEPAPERBACK_NAME);
        assertThrows(TransactionSystemException.class, () -> {
            tradePaperbackRepository.save(tradePaperback);
        });
    }

    @Test
    void saveTradePaperback() {
        Comic comic = TestConstants.getComicWithoutReferences(comicService);
        assertEquals(0, comic.getTradePaperbacks().size());
        TradePaperback tradePaperback = new TradePaperback();
        tradePaperback.setName(TestConstants.TRADEPAPERBACK_NAME);
        tradePaperback.setComic(comic);
        TradePaperback savedInstance = tradePaperbackRepository.save(tradePaperback);
        assertNotNull(savedInstance);
        comicService.deleteTradePaperBack(savedInstance);
        assertEquals(0, comic.getTradePaperbacks().size());
    }
}
