import SwiftRs
import Tauri
import UIKit
import WebKit

class SaveTokenArgs: Decodable {
    var token: String?
}

let appGroupID = "group.com.haystack.app"
let sharedTokenKey = "sharedAuthToken"

class SharedToken: Plugin {
    @objc func save_token(_ invoke: Invoke) throws {
        guard let args = try? invoke.parseArgs(SaveTokenArgs.self), let token = args.token else {
            invoke.reject("Missing token argument")
            return
        }

        // Access shared UserDefaults
        guard let sharedDefaults = UserDefaults(suiteName: appGroupID) else {
            invoke.reject("Could not access shared UserDefaults. Check App Group configuration.")
            return
        }

        sharedDefaults.set(token, forKey: sharedTokenKey)
        invoke.resolve()
    }
}

@_cdecl("init_plugin_ios_shared_token")
func initPlugin() -> Plugin {
  return SharedToken()
}
