package org.fuseri.moduleexercise.question;

import org.fuseri.moduleexercise.exercise.Exercise;
import org.fuseri.moduleexercise.exercise.ExerciseRepository;
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
public class QuestionRepositoryTest {

    @Autowired
    QuestionRepository repository;

    @Autowired
    ExerciseRepository exerciseRepository;

    @Autowired
    TestEntityManager entityManager;


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

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

    @BeforeEach
    void init() {
        exerciseRepository.save(exercise);
    }

    @Test
    void saveQuestion() {
        Question saved = repository.save(question);

        Assertions.assertNotNull(saved);
        Assertions.assertEquals(question, saved);
    }

    @Test
    void findById() {
        entityManager.persist(question);
        entityManager.flush();

        Question found = repository.findById(question.getId()).orElse(null);

        Assertions.assertNotNull(found);
        Assertions.assertEquals(found, question);
    }


    @Test
    void testFindAllQuestions() {
        entityManager.persist(question);
        entityManager.persist(question2);

        Page<Question> coursePage = repository.findAll(PageRequest.of(0, 42));

        Assertions.assertEquals(2, coursePage.getTotalElements());
        Assertions.assertEquals(coursePage.getContent(), Arrays.asList(question, question2));
    }
    @Test
    void testFindAllQuestionsEmpty() {
        Page<Question> coursePage = repository.findAll(PageRequest.of(0, 42));

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

    @Test
    void testDeleteQuestion() {
        Long id = entityManager.persist(question).getId();
        entityManager.flush();

        repository.deleteById(id);

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