//
//  SharedImagePlugin.swift
//  App
//
//  Capacitor plugin for accessing shared image data from Share Extension
//

import Foundation
import Capacitor

@objc(SharedImage)
public class SharedImagePlugin: CAPPlugin, CAPBridgedPlugin {
    
    // MARK: - CAPBridgedPlugin Conformance
    
    public var identifier: String {
        return "SharedImage"
    }
    
    public var jsName: String {
        return "SharedImage"
    }
    
    public var pluginMethods: [CAPPluginMethod] {
        return [
            CAPPluginMethod(#selector(getSharedImage(_:)), returnType: .promise),
            CAPPluginMethod(#selector(hasSharedImage(_:)), returnType: .promise)
        ]
    }
    
    // MARK: - Plugin Methods
    
    /**
     * Get shared image data from App Group UserDefaults
     * Returns base64 string and fileName, or null if no image exists
     * Clears the data after reading to prevent re-reading
     */
    @objc public func getSharedImage(_ call: CAPPluginCall) {
        guard let sharedData = SharedImageUtility.getSharedImageData() else {
            // No shared image exists - return null (not an error)
            call.resolve([
                "base64": NSNull(),
                "fileName": NSNull()
            ])
            return
        }
        
        // Return the shared image data
        call.resolve([
            "base64": sharedData["base64"] ?? "",
            "fileName": sharedData["fileName"] ?? ""
        ])
    }
    
    /**
     * Check if shared image exists without reading it
     * Useful for quick checks before calling getSharedImage()
     */
    @objc public func hasSharedImage(_ call: CAPPluginCall) {
        let hasImage = SharedImageUtility.hasSharedImage()
        call.resolve([
            "hasImage": hasImage
        ])
    }
}

