package com.zioinfo.kintex.system.role;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/** 역할/권한(RBAC) 관리. 역할-권한 매핑을 통째로 교체(clear+insert)로 갱신한다. */
@Service
public class RoleService {

    private final RoleMapper mapper;

    public RoleService(RoleMapper mapper) {
        this.mapper = mapper;
    }

    public List<RoleDto> roles() {
        return mapper.findRoles().stream().map(r -> {
            String code = str(r.get("roleCode"));
            return new RoleDto(code, str(r.get("roleName")), str(r.get("description")),
                    str(r.get("useYn")), mapper.findRolePermissions(code));
        }).toList();
    }

    public List<PermissionDto> permissions() {
        return mapper.findPermissions().stream().map(r -> new PermissionDto(
                str(r.get("permCode")), str(r.get("permName")), str(r.get("description")))).toList();
    }

    @Transactional
    public void save(RoleDto role) {
        Map<String, Object> p = new HashMap<>();
        p.put("roleCode", role.roleCode());
        p.put("roleName", role.roleName());
        p.put("description", role.description());
        p.put("useYn", role.useYn());
        mapper.upsertRole(p);
        mapper.clearRolePermissions(role.roleCode());
        if (role.permissions() != null) {
            for (String perm : role.permissions()) {
                mapper.addRolePermission(role.roleCode(), perm);
            }
        }
    }

    @Transactional
    public void delete(String roleCode) {
        mapper.deleteRole(roleCode);
    }

    private static String str(Object o) { return o == null ? null : String.valueOf(o); }
}
