//
//  RolePermissionMatcher.swift
//  suixinkan
//

import Foundation

/// 角色权限匹配器，在 `role-permission` 列表中定位当前账号角色。
enum RolePermissionMatcher {

    /// 按 role_code → legacy id → role_name 优先级匹配权限项。
    static func match(
        in list: [RolePermissionResponse],
        roleCode: String,
        roleName: String,
        legacyRoleId: Int = 0
    ) -> RolePermissionResponse? {
        if let role = AppRoleCode.fromCode(roleCode),
           let matched = list.first(where: { AppRoleCode.fromCode($0.role.roleCode) == role }) {
            return matched
        }

        if legacyRoleId > 0,
           let matched = list.first(where: { $0.role.id == legacyRoleId }) {
            return matched
        }

        let trimmedName = roleName.trimmingCharacters(in: .whitespacesAndNewlines)
        if !trimmedName.isEmpty {
            return list.first { item in
                let itemName = item.role.name.trimmingCharacters(in: .whitespacesAndNewlines)
                guard !itemName.isEmpty else { return false }
                return itemName.contains(trimmedName) || trimmedName.contains(itemName)
            }
        }

        return nil
    }
}
