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.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
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;

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

    @Autowired
    private WorktypeRepository worktypeRepository;

    @Test
    @Order(1)
    void checkInitialDataLoad() {
        List<Worktype> worktypes = worktypeRepository.findAll();
        assertEquals(3, worktypes.size());
    }

    @Test
    @Order(2)
    void findWorktypeByName() {
        Worktype found = worktypeRepository.findByName(TestConstants.WORKTYPE_INKER);
        assertNotNull(found);
        assertEquals(TestConstants.WORKTYPE_INKER, found.getName());
        Worktype notFound = worktypeRepository.findByName("er");
        assertNull(notFound);
    }

    @Test
    @Order(3)
    void throwExceptionWhenArtistSavedWithEmptyName() {
        Worktype worktype1 = new Worktype();
        assertThrows(TransactionSystemException.class, () -> {
            worktypeRepository.save(worktype1);
        });
    }

    @Test
    @Order(4)
    void saveWorktypeWithIdenticalName() {
        Worktype worktype1 = new Worktype();
        worktype1.setName(TestConstants.WORKTYPE_NAME);
        worktypeRepository.save(worktype1);
        Worktype worktype2 = new Worktype();
        worktype2.setName(TestConstants.WORKTYPE_NAME);
        assertThrows(DataIntegrityViolationException.class, () -> {
            worktypeRepository.save(worktype2);
        });
        worktypeRepository.delete(worktype1);
    }

    @Test
    @Order(5)
    void saveWorktype() {
        Worktype worktype = new Worktype();
        worktype.setName(TestConstants.WORKTYPE_NAME);
        worktypeRepository.save(worktype);
        assertEquals(TestConstants.WORKTYPE_COUNT + 1, worktypeRepository.count());
    }

    @Test
    @Order(6)
    void deleteWorktype() {
        Worktype worktype = worktypeRepository.findByName(TestConstants.WORKTYPE_NAME);
        assertNotNull(worktype);
        worktypeRepository.delete(worktype);
        assertEquals(TestConstants.WORKTYPE_COUNT, worktypeRepository.count());
    }
}
