import Foundation
import Capacitor
import GoogleSignIn

@objc(CapacitorNativeGoogleAuthPlugin)
public class CapacitorNativeGoogleAuthPlugin: CAPPlugin, CAPBridgedPlugin {

    public let identifier = "CapacitorNativeGoogleAuthPlugin"
    public let jsName = "CapacitorNativeGoogleAuth"
    public let pluginMethods: [CAPPluginMethod] = [
        CAPPluginMethod(name: "signIn", returnType: CAPPluginReturnPromise)
    ]

    private let implementation = CapacitorNativeGoogleAuth()

    @objc func signIn(_ call: CAPPluginCall) {

        guard let clientId = bridge?.config.getString("plugins.CapacitorNativeGoogleAuth.iosClientId") else {
            call.reject("Missing iosClientId in capacitor.config.ts")
            return
        }

        guard let presentingVC = bridge?.viewController else {
            call.reject("No presenting view controller")
            return
        }

        implementation.signIn(presentingVC: presentingVC, clientId: clientId) { token, error in

            if let error = error {
                call.reject("Google Sign-In failed", error)
                return
            }

            guard let token = token else {
                call.reject("No ID token returned")
                return
            }

            call.resolve([
                "idToken": token
            ])
        }
    }
}
