package org.fuseri.moduleexercise.answer;

import org.fuseri.moduleexercise.exercise.Exercise;
import org.fuseri.moduleexercise.question.Question;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;

@DataJpaTest
class AnswerRepositoryTest {

    @Autowired
    AnswerRepository answerRepository;

    @Autowired
    TestEntityManager entityManager;

    Exercise exercise = new Exercise("name", "desc", 2, 1L, new HashSet<>());

    Question question = new Question("text", new HashSet<>(), exercise);

    Answer answer = new Answer("text", false, question);
    Answer answer2 = new Answer("text2", true, question);

    @BeforeEach
    void init() {
        entityManager.persist(exercise);
        entityManager.persist(question);
    }

    @Test
    void saveAnswer() {
        Answer createdAnswer = answerRepository.save(answer);

        Assertions.assertNotNull(createdAnswer);
        Assertions.assertEquals(answer, createdAnswer);
    }

    @Test
    void findByQuestionId() {
        entityManager.persist(answer);
        entityManager.flush();

        Answer foundAnswer = answerRepository.findById(answer.getId()).orElse(null);

        Assertions.assertNotNull(foundAnswer);
        Assertions.assertEquals(foundAnswer, answer);
    }

    @Test
    void testFindAllQuestions() {
        entityManager.persist(exercise);
        entityManager.persist(question);
        entityManager.persist(answer);
        entityManager.persist(answer2);
        entityManager.flush();

        Page<Answer> coursePage = answerRepository.findAll(PageRequest.of(0, 42));

        Assertions.assertEquals(2, coursePage.getTotalElements());
        Assertions.assertEquals(coursePage.getContent(), Arrays.asList(answer, answer2));
    }

    @Test
    void testFindAllQuestionsEmpty() {
        Page<Answer> coursePage = answerRepository.findAll(PageRequest.of(0, 42));

        Assertions.assertEquals(0, coursePage.getTotalElements());
        Assertions.assertEquals(coursePage.getContent(), new ArrayList<>());
    }

    @Test
    void testDeleteAnswer() {
        Long id = entityManager.persist(answer).getId();
        entityManager.flush();

        answerRepository.deleteById(id);

        Assertions.assertTrue(answerRepository.findById(id).isEmpty());
    }

}
