package cz.muni.fi.pa165.soccermanager.repository;

import cz.muni.fi.pa165.soccermanager.PersistenceApplication;
import cz.muni.fi.pa165.soccermanager.entity.Match;
import cz.muni.fi.pa165.soccermanager.entity.Team;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import org.springframework.transaction.annotation.Transactional;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.time.LocalDate;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.testng.AssertJUnit.assertEquals;

/**
 * @author Stanislav Koshchienko (uco: 506549)
 */
@Transactional
@ContextConfiguration(classes = PersistenceApplication.class)
@TestExecutionListeners(TransactionalTestExecutionListener.class)
public class MatchRepositoryTest extends AbstractTestNGSpringContextTests {
    private final LocalDate DATE1 = LocalDate.of(2022, 3, 26);
    private final LocalDate DATE2 = LocalDate.of(2022, 6, 18);

    @PersistenceContext
    protected EntityManager em;

    @Autowired
    private MatchRepository matchRepository;

    @Autowired
    private TeamRepository teamRepository;

    private Match match1;
    private Match match2;
    private Team team;

    @BeforeMethod
    public void setUp() {
        match1 = new Match();
        match1.setStartDate(DATE1);
        match1.setPlayPlace("Brno");

        match2 = new Match();
        match2.setStartDate(DATE2);
        match2.setPlayPlace("Prague");

        team = new Team("1");
        team.setGround("");
        teamRepository.saveAndFlush(team);

        match1.setDefender(team);
        match1.setChallenger(team);

        match2.setDefender(team);
        match2.setChallenger(team);

        em.persist(match1);
        em.persist(match2);
    }

    @Rollback
    @Test
    public void createTest() {
        final var m = new Match();
        m.setStartDate(LocalDate.of(2019, 6, 18));
        m.setPlayPlace("Berlin");
        m.setChallenger(team);
        m.setDefender(team);
        matchRepository.save(m);

        final var createdMatch = em.find(Match.class, m.getId());
        assertThat(createdMatch).isEqualTo(m);
    }

    @Test
    public void findAllTest() {
        assertEquals(List.of(match1, match2), matchRepository.findAll());
    }

    @Rollback
    @Test
    public void removeTest() {
        matchRepository.delete(match1);
        assertEquals(List.of(match2), matchRepository.findAll());
    }
}