package org.fuseri.moduleexercise.exercise;

import org.junit.jupiter.api.Assertions;
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.Arrays;
import java.util.HashSet;

@DataJpaTest
class ExerciseRepositoryTest {

    @Autowired
    ExerciseRepository exerciseRepository;

    @Autowired
    TestEntityManager entityManager;

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

    @Test
    void saveExercise() {
        Exercise saved = exerciseRepository.save(exercise);

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

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

        Exercise found = exerciseRepository.findById(exercise.getId()).orElse(null);

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


    @Test
    void findByCourseIdAndDifficulty() {
        entityManager.persist(exercise);
        entityManager.flush();

        Page<Exercise> found = exerciseRepository.findByCourseIdAndDifficulty(1L, 2, PageRequest.of(0, 10));

        Assertions.assertEquals(1, found.getTotalElements());
        Assertions.assertEquals(found.getContent().get(0), exercise);
    }

    @Test
    void testFindAllExercises() {
        Exercise exercise1 = new Exercise();

        entityManager.persist(exercise);
        entityManager.persist(exercise1);
        entityManager.flush();

        Page<Exercise> coursePage = exerciseRepository.findAll(PageRequest.of(0, 42));

        Assertions.assertEquals(2, coursePage.getTotalElements());
        Assertions.assertEquals(coursePage.getContent(), Arrays.asList(exercise, exercise1));
    }

    @Test
    void testDeleteExercise() {
        Long id = entityManager.persist(exercise).getId();
        entityManager.flush();

        exerciseRepository.deleteById(id);

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

}
