//
//  PermissionApplyStatusViewModel.swift
//  suixinkan
//

import Foundation

/// 权限申请审核状态 ViewModel，对齐 Android `PermissionApplyStatusViewModel`。
final class PermissionApplyStatusViewModel {

    private(set) var pendingData: RoleApplyPendingResponse?
    private(set) var isLoading = false
    private(set) var rolePermissionList: [RolePermissionResponse] = []
    private(set) var showScenicListDialog = false
    private(set) var dialogRoleName = ""
    private(set) var dialogScenicList: [ScenicInfo] = []

    var onStateChange: (() -> Void)?
    var onNavigateToEdit: ((RoleApplyPendingResponse) -> Void)?

    private let applyCode: String
    private let appStore: AppStore

    init(applyCode: String, appStore: AppStore = .shared) {
        self.applyCode = applyCode
        self.appStore = appStore
        rolePermissionList = appStore.permissions.rolePermissionList()
    }

    func loadPendingData(api: HomeAPI) async {
        isLoading = true
        notifyStateChange()
        do {
            let pendingList = try await api.roleApplyPending()
            pendingData = pendingList.first {
                $0.code == applyCode
                    && ($0.status == PermissionApplyPendingStatus.reviewing
                        || $0.status == PermissionApplyPendingStatus.rejected)
            }
        } catch {
            pendingData = nil
        }
        isLoading = false
        notifyStateChange()
    }

    func navigateToEditIfRejected() {
        guard let pendingData, pendingData.status == PermissionApplyPendingStatus.rejected else { return }
        onNavigateToEdit?(pendingData)
    }

    /// 展示某个已有角色的全部景区。
    func showScenicList(roleName: String, scenics: [ScenicInfo]) {
        dialogRoleName = roleName
        dialogScenicList = scenics
        showScenicListDialog = true
        notifyStateChange()
    }

    /// 关闭已有景区列表弹窗。
    func hideScenicList() {
        dialogRoleName = ""
        dialogScenicList = []
        showScenicListDialog = false
        notifyStateChange()
    }

    private func notifyStateChange() {
        onStateChange?()
    }
}
