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 VolumeTest {

    @Autowired
    private VolumeRepository volumeRepository;

    @Autowired
    private ComicRepository comicRepository;

    @Autowired
    private ComicService comicService;

    @Test
    void checkInitialDataLoad() {
        assertEquals(TestConstants.VOLUME_COUNT, volumeRepository.count());
    }

    @Test
    void exceptionThrownWhenSavingVolumeWithEmptyName() {
        Comic comic = TestConstants.getComicWithoutReferences(comicService);
        Volume volume = new Volume();
        volume.setComic(comic);
        assertThrows(TransactionSystemException.class, () -> {
            volumeRepository.save(volume);
        });
    }

    @Test
    void exceptionThrownWhenSavingVolumeWithoutComic() {
        Volume volume = new Volume();
        volume.setName(TestConstants.VOLUME_NAME);
        assertThrows(TransactionSystemException.class, () -> {
            volumeRepository.save(volume);
        });
    }

    @Test
    void saveVolume() {
        Comic comic = TestConstants.getComicWithoutReferences(comicService);
        assertEquals(0, comic.getVolumes().size());
        Volume volume = new Volume();
        volume.setName(TestConstants.VOLUME_NAME);
        volume.setComic(comic);
        Volume savedInstance = volumeRepository.save(volume);
        assertNotNull(savedInstance);
        comicService.deleteVolume(savedInstance);
        assertEquals(0, comic.getVolumes().size());
        assertEquals(TestConstants.VOLUME_COUNT, volumeRepository.count());
    }
}
