import Combine
import Foundation

@MainActor
class LicenseViewModel: ObservableObject {
    enum LicenseState: Equatable {
        case trial(daysRemaining: Int)
        case trialExpired
        case licensed
    }

    @Published private(set) var licenseState: LicenseState = .licensed
    @Published var licenseKey: String = ""
    @Published var isValidating = false
    @Published var validationMessage: String?
    @Published var validationSuccess = true
    @Published private(set) var activationsLimit = 0

    private let userDefaults = UserDefaults.standard
    private let licenseManager = LicenseManager.shared

    init() {
        licenseState = .licensed
    }

    func startTrial() {
        licenseState = .licensed
        NotificationCenter.default.post(name: .licenseStatusChanged, object: nil)
    }

    var canUseApp: Bool {
        true
    }

    func openPurchaseLink() {
        validationSuccess = true
        validationMessage = "Proat gebruikt geen licentie of aankoopflow."
    }

    func validateLicense() async {
        isValidating = true
        defer { isValidating = false }

        licenseState = .licensed
        validationSuccess = true
        validationMessage = "Proat is klaar voor gebruik."
        NotificationCenter.default.post(name: .licenseStatusChanged, object: nil)
    }

    func removeLicense() {
        licenseManager.removeAll()
        userDefaults.set(false, forKey: "VoiceInkLicenseRequiresActivation")
        userDefaults.set(false, forKey: "VoiceInkHasLaunchedBefore")
        userDefaults.activationsLimit = 0

        licenseKey = ""
        activationsLimit = 0
        licenseState = .licensed
        validationSuccess = true
        validationMessage = "Oude licentiegegevens zijn verwijderd. Proat blijft vrij beschikbaar."
        NotificationCenter.default.post(name: .licenseStatusChanged, object: nil)
    }
}

extension UserDefaults {
    var activationsLimit: Int {
        get { integer(forKey: "VoiceInkActivationsLimit") }
        set { set(newValue, forKey: "VoiceInkActivationsLimit") }
    }
}
