//
//  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] = []

    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.rolePermissionList()
    }

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

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

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