//
//  EventInteractor.swift
//  AirbridgeReactNative
//
//  Created by WOF on 7/8/24.
//  Copyright © 2024 ab180. All rights reserved.
//

import Foundation
import React
import Airbridge

@objc(EventInteractor)
class EventInteractor: NSObject {
    @objc(trackEvent:semanticAttributes:customAttributes:)
    func trackEvent(
        _ category: String,
        _ semanticAttributes: [String: Any]?,
        _ customAttributes: [String: Any]?
    ) {
        Airbridge.trackEvent(
            category: category,
            semanticAttributes: semanticAttributes ?? [:],
            customAttributes: customAttributes ?? [:]
        )
    }

    @objc(setAdditionalEventAttributes:semanticAttributes:customAttributes:)
    func setAdditionalEventAttributes(
        _ types: [String],
        _ semanticAttributes: [String: Any]?,
        _ customAttributes: [String: Any]?
    ) {
        let eventTypes = types.compactMap(convertAirbridgeEventType(type:))
        guard !eventTypes.isEmpty else { return }

        Airbridge.setAdditionalEventAttributes(
            types: eventTypes,
            semanticAttributes: semanticAttributes,
            customAttributes: customAttributes
        )
    }

    @objc(trackStoreInAppPurchaseEvent:semanticAttributes:customAttributes:)
    func trackStoreInAppPurchaseEvent(
        _ purchase: [String: Any],
        _ semanticAttributes: [String: Any]?,
        _ customAttributes: [String: Any]?
    ) {
        Airbridge.trackStoreInAppPurchaseEvent(
            AirbridgeStoreInAppPurchase(object: purchase),
            semanticAttributes: semanticAttributes,
            customAttributes: customAttributes
        )
    }

    func convertAirbridgeEventType(type: String) -> AirbridgeEventType? {
        switch type {
        case "INSTALL": return .install
        case "OPEN": return .open
        case "DEEPLINK_OPEN": return .deeplinkOpen
        default:
            Logger.warning("Unknown event type: \(type)")
            return nil
        }
    }
}
