package com.njcn.rdms.module.system.framework.permission;

import com.njcn.rdms.framework.common.enums.CommonStatusEnum;
import com.njcn.rdms.module.system.dal.dataobject.permission.RoleDO;
import com.njcn.rdms.module.system.enums.permission.ObjectRoleConstants;
import com.njcn.rdms.module.system.enums.permission.PermissionScopeTypeEnum;
import com.njcn.rdms.module.system.service.permission.RoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

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

/**
 * 启动时校验 {@link ObjectRoleConstants} 列出的内置对象角色，要求 system_role 表里全部存在、启用、object_type 匹配。
 * 缺一抛 IllegalStateException 让进程退出 —— 避免运行期按 code 查不到才暴雷。
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class ObjectRoleStartupValidator implements ApplicationRunner {

    private final RoleService roleService;

    @Override
    public void run(ApplicationArguments args) {
        List<String> errors = new ArrayList<>();
        for (ObjectRoleConstants required : ObjectRoleConstants.values()) {
            RoleDO role = roleService.getRoleByCode(
                    required.getCode(),
                    PermissionScopeTypeEnum.OBJECT.getScopeType(),
                    required.getObjectType());
            if (role == null) {
                errors.add(String.format("缺失 [%s/%s] (object_type=%s)",
                        required.getCode(), required.getName(), required.getObjectType()));
                continue;
            }
            if (!CommonStatusEnum.ENABLE.getStatus().equals(role.getStatus())) {
                errors.add(String.format("已停用 [%s/%s]", required.getCode(), required.getName()));
            }
        }
        if (!errors.isEmpty()) {
            String detail = String.join("\n  - ", errors);
            log.error("[ObjectRoleStartupValidator] 内置对象角色校验失败:\n  - {}", detail);
            throw new IllegalStateException("内置对象角色校验失败，请检查 system_role 后重启:\n  - " + detail);
        }
        log.info("[ObjectRoleStartupValidator] 内置对象角色 {} 条全部就位",
                ObjectRoleConstants.values().length);
    }

}
