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.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 IssueTest {

    @Autowired
    private IssueRepository issueRepository;

    @Autowired
    private ComicService comicService;

    @Test
    void checkInitialDataLoad() {
        List<Issue> issues = comicService.findAllIssues();
        assertEquals(TestConstants.ISSUE_COUNT, issues.size());
    }

    @Test
    void exceptionThrownWhenSavingIssueWithEmptyNumber() {
        Comic comic = TestConstants.getComicWithoutReferences(comicService);
        assertNotNull(comic);
        Issue issue = new Issue();
        issue.setComic(comic);
        assertThrows(TransactionSystemException.class, () -> {
            issueRepository.save(issue);
        });
    }

    @Test
    void exceptionThrownWhenSavingStoryArcWithoutComic() {
        Issue issue = new Issue();
        issue.setIssueNumber(TestConstants.ISSUE_ISSUENUMBER);
        assertThrows(TransactionSystemException.class, () -> {
            issueRepository.save(issue);
        });
    }

    @Test
    void saveStoryArc() {
        Comic comic = TestConstants.getComicWithoutReferences(comicService);
        assertEquals(0, comic.getStoryArcs().size());
        Issue issue = new Issue();
        issue.setComic(comic);
        issue.setIssueNumber(TestConstants.ISSUE_ISSUENUMBER);
        Issue savedInstance = issueRepository.save(issue);
        assertNotNull(savedInstance);
        comicService.deleteIssue(savedInstance);
        assertEquals(0, comic.getStoryArcs().size());
    }
}
