package cn.reghao.devops.web.admin;

import cn.reghao.devops.web.WebApplication;
import cn.reghao.devops.web.admin.account.db.repository.MenuRepository;
import cn.reghao.devops.web.admin.account.db.repository.RoleRepository;
import cn.reghao.devops.web.admin.account.db.repository.UserRepository;
import cn.reghao.devops.web.admin.account.model.constant.RoleType;
import cn.reghao.devops.web.admin.account.model.dto.CreateAccountDto;
import cn.reghao.devops.web.admin.account.model.po.Menu;
import cn.reghao.devops.web.admin.account.model.po.Role;
import cn.reghao.devops.web.admin.account.model.po.User;
import cn.reghao.devops.web.admin.account.service.AccountService;
import cn.reghao.jutil.jdk.security.RandomString;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * @author reghao
 * @date 2022-08-17 15:53:04
 */
@Slf4j
@ActiveProfiles("dev")
@SpringBootTest(classes = WebApplication.class)
@RunWith(SpringRunner.class)
public class AccountTest {
    @Autowired
    AccountService accountService;
    @Autowired
    UserRepository userRepository;
    @Autowired
    RoleRepository roleRepository;
    @Autowired
    MenuRepository menuRepository;

    @Test
    public void initRole() {
        List<Role> roleList = roleRepository.findAll();
        if (roleList.isEmpty()) {
            roleList = new ArrayList<>();
            for (RoleType roleType : RoleType.values()) {
                roleList.add(new Role(roleType.name(), roleType.getDesc()));
            }
            roleRepository.saveAll(roleList);

            List<Menu> menus = menuRepository.findAll();
            if (!menus.isEmpty()) {
                Role role = roleRepository.findByName(RoleType.ROLE_ADMIN.name());
                role.setMenus(new HashSet<>(menus));
                roleRepository.save(role);
            }
        }
    }

    @Test
    public void initAccount() {
        List<User> list = userRepository.findAll(PageRequest.of(0, 1)).getContent();
        if (list.isEmpty()) {
            String username = "admin";
            String password = RandomString.getString(10);
            Role role = roleRepository.findByName(RoleType.ROLE_ADMIN.name());
            if (role != null) {
                int roleId = role.getId();
                CreateAccountDto createAccountDto = new CreateAccountDto(username, password, roleId);
                accountService.createAccount(createAccountDto);
                log.info("初始化完成, 帐号和密码分别是 {} 和 {}", username, password);
            }
        }
    }
}
