package com.zsc.edu.gateway.service.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zsc.edu.gateway.domain.system.RoleBuilder;
import com.zsc.edu.gateway.exception.ConstraintException;
import com.zsc.edu.gateway.modules.system.dto.RoleDto;
import com.zsc.edu.gateway.modules.system.entity.Dept;
import com.zsc.edu.gateway.modules.system.entity.Role;
import com.zsc.edu.gateway.modules.system.repo.AuthorityRepository;
import com.zsc.edu.gateway.modules.system.repo.RoleRepository;
import com.zsc.edu.gateway.modules.system.service.RoleService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import jakarta.annotation.Resource;
import java.util.Arrays;
import java.util.HashSet;

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

/**
 * @author harry yao
 */
//@ActiveProfiles("test")
@SpringBootTest
class RoleServiceTest {

    @Autowired
    private RoleService service;

    @Resource
    private RoleRepository repo;

    private Role role1;
    private Role role2;

    @BeforeEach
    void setUp() {
        role1 = RoleBuilder.aRole().name("A超级管理员").build();
        repo.insert(role1);
        role2 = RoleBuilder.aRole().name("A普通用户").build();
        repo.insert(role2);
    }

    @AfterEach
    void tearDown() {
        repo.delete(new LambdaQueryWrapper<Role>().in(Role::getName, "A超级管理员", "A普通用户", "A公司CEO", "A项目经理", "A超级管理员2"));
    }

    @Test
    void list() {
        assertEquals(2, service.list(new LambdaQueryWrapper<Role>().like(Role::getName, "A")).size());
        assertEquals(1, service.list(new LambdaQueryWrapper<Role>().eq(Role::getName, role1.getName())).size());
//        assertEquals(1, service.list().size());
    }

    @Test
    void create() {
        RoleDto dto = new RoleDto();
        dto.setName("A公司CEO");
        dto.setRemark("remark...");
//        dto.setAuthorities(null);
        Role Role = service.create(dto);
        assertNotNull(Role.getId());
        assertEquals(3, service.list(new QueryWrapper<Role>().like("name", "A")).size());
        // 不能创建其他已存在的同名同代码部门
        assertThrows(ConstraintException.class, () -> service.create(new RoleDto(role1.getName(), "remark...", null)));
    }

    @Test
    void update() {
        RoleDto dto = new RoleDto();
        dto.setName("A超级管理员2");
        dto.setRemark("remark...");
//        dto.setAuthorities(null);
//        assertTrue(service.edit(dto, role2.id));
    }
}
