package org.fuseri.modulelanguageschool.course;

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.ArrayList;
import java.util.Arrays;
import java.util.List;

@DataJpaTest
class CourseRepositoryTest {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private CourseRepository courseRepository;

    private final Course course =  new Course("AJ1", 10,
            Language.ENGLISH, ProficiencyLevel.A1);

    @Test
    void saveCourse() {
        Course saved = courseRepository.save(course);

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

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

        Course found = courseRepository.findById(course.getId()).orElse(null);

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


    @Test
    void findAllByLang() {
        entityManager.persist(course);
        entityManager.flush();

        List<Course> found = courseRepository.findAllByLang(course.getLanguage());

        Assertions.assertEquals(1, found.size());
        Assertions.assertEquals(found.get(0), course);
    }

    @Test
    void findAllByLangProf() {
        entityManager.persist(course);
        entityManager.flush();

        List<Course> found = courseRepository.findAllByLangProf(course.getLanguage(), course.getProficiency());

        Assertions.assertEquals(1, found.size());
        Assertions.assertEquals(found.get(0), course);
    }
    @Test
    public void testFindAllCourses() {
        Course course1 = new Course();
        Course course2 = new Course();

        courseRepository.save(course1);
        courseRepository.save(course2);

        Page<Course> coursePage = courseRepository.findAll(PageRequest.of(0, 42));

        Assertions.assertEquals(2, coursePage.getTotalElements());
        Assertions.assertEquals(coursePage.getContent(), Arrays.asList(course1, course2));
    }

    @Test
    public void testDeleteCourse() {
        Long courseId = entityManager.persist(new Course()).getId();
        entityManager.flush();

        courseRepository.deleteById(courseId);

        Assertions.assertTrue(courseRepository.findById(courseId).isEmpty());
    }

}
