/*
 * Copyright (c) 2025 SimcuTeam. All rights reserved.
 * 遵循 MIT 许可证。
 * AuthSDK/SimApiAuthIam：权限中心远程 SDK。
 */

package simcu::simapi.authsdk

import std.collection.*
import simcu::simapi.communications.*
import simcu::simapi.helpers.*

/**
 * 权限中心远程 SDK：
 * 注册权限点 / 获取权限标识 / 校验权限。
 */
public class SimApiAuthIam {
    private let _client: SimApiAuthClient

    public init(client: SimApiAuthClient) {
        this._client = client
    }

    /**
     * 向 IAM 注册权限。
     */
    public func registerPermissions(permissions: Array<PermissionItem>): Unit {
        // 请求体：{"permissions":[{"identifier":...,"name":...,"group":...,"description":...},...]}
        var items = ArrayList<Any>()
        for (p in permissions) {
            var item = HashMap<String, Any>()
            item["identifier"] = p.identifier
            item["name"] = p.name
            item["group"] = p.group
            item["description"] = p.description
            items.add(item)
        }
        var body = HashMap<String, Any>()
        body["permissions"] = items.toArray()
        _client.signQuery<String>("/api/iam/permission/register", body: SimApiUtil.json(Some(body)))
    }

    /**
     * 获取拥有的权限标识数组。
     */
    public func getPermissionOwned(profileId: String, groupId!: ?String = None): Array<String> {
        var body = HashMap<String, Any>()
        body["profileId"] = profileId
        if (let Some(groupId) <- groupId) {
            body["groupId"] = groupId
        }
        _client.signQuery<Array<String>>("/api/iam/permission/owned", body: SimApiUtil.json(Some(body)))
    }

    /**
     * 检测 profileId 是否有该权限，无权限抛 403。
     */
    public func checkPermission(profileId: String, permission: String, groupId!: ?String = None): Unit {
        var body = HashMap<String, Any>()
        body["profileId"] = profileId
        body["permission"] = permission
        if (let Some(groupId) <- groupId) {
            body["groupId"] = groupId
        }
        let ok = _client.signQuery<Bool>("/api/iam/permission/check", body: SimApiUtil.json(Some(body)))
        SimApiError.errorWhen(!ok, code: 403, message: "没有该权限")
    }
}
