package enea.lecservice.repository;

import enea.lecservice.entities.Permission;
import enea.lecservice.entities.Role;
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 java.util.List;

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

@ExtendWith(SpringExtension.class)
@DataJpaTest(properties = {
        "logging.level.ROOT= WARN",
        "logging.level.org.springframework.test.context.transaction= INFO",
        "logging.level.org.hibernate.SQL= DEBUG"
})
class PermissionRepositoryTest {
    @Autowired TestEntityManager testEntityManager;
    @Autowired PermissionRepository permissionRepository;
    @Autowired RoleRepository roleRepository;

    @BeforeEach
    public void before() {
        var adminPermission = Permission.builder().id("admin").build();
        var viewPermission = Permission.builder().id("view").build();
        var role = Role.builder().id("platform-admin").permissions(
                Arrays.asList(adminPermission, viewPermission)
        ).build();
        permissionRepository.save(adminPermission);
        permissionRepository.save(viewPermission);
        roleRepository.save(role);
        testEntityManager.flush();
        testEntityManager.clear();
    }

    @Test
    public void shouldRetrievePermissionsByRoles() {
        List<String> roles = Collections.singletonList("platform-admin");
        var permissions = permissionRepository.findPermissionsByRolesDescription(roles);
        assertEquals(2, permissions.size());
    }
}