package enea.lecservice.repository;

import enea.lecservice.entities.Page;
import enea.lecservice.entities.Permission;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
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.test.context.junit.jupiter.SpringExtension;

import java.util.Arrays;
import java.util.Collections;

import static org.junit.jupiter.api.Assertions.assertEquals;

@ExtendWith(SpringExtension.class)
@DataJpaTest(properties = {
        "logging.level.ROOT= WARN",
        "logging.level.org.springframework.test.context.transaction= INFO",
        "logging.level.org.hibernate.SQL= DEBUG"
})
class PageRepositoryTest {

    @Autowired
    TestEntityManager testEntityManager;
    @Autowired
    PageRepository pageRepository;
    @Autowired
    PermissionRepository permissionRepository;

    @BeforeEach
    void setUp() {
        permissionRepository.save(Permission.builder().id("admin").build());
        permissionRepository.save(Permission.builder().id("view").build());
        pageRepository.save(Page.builder().lang("it").visible(true).name("Page1").permissionId("view").build());
        pageRepository.save(Page.builder().lang("it").visible(true).name("Page2").permissionId("view").build());
        pageRepository.save(Page.builder().lang("it").visible(true).name("Page3").permissionId("admin").build());
        testEntityManager.flush();
        testEntityManager.clear();
    }

    @Test
    void shouldRetrievePagesBasedOnPermissions() {
        var pages = pageRepository.getPagesInPermissions("it", Collections.singletonList("view"));
        assertEquals(2, pages.size());
        pages = pageRepository.getPagesInPermissions("it", Arrays.asList("view", "admin"));
        assertEquals(3, pages.size());
    }
}