//
//  AnalyticsService.swift
//  CasinoKit
//

import Foundation

public actor AnalyticsService: AnalyticsTracking {
    private var endpoint: URL?

    public init(endpoint: URL? = nil) {
        self.endpoint = endpoint
    }

    public func updateEndpoint(_ endpoint: URL?) async {
        self.endpoint = endpoint
    }

    public func track(_ event: AnalyticsEvent) async {
        guard let endpoint else { return }

        var request = URLRequest(url: endpoint)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        let payload = AnalyticsPayload(
            appIdentifier: AppContext.bundleIdentifier,
            appVersion: AppContext.appVersion,
            buildNumber: AppContext.buildNumber,
            event: event
        )

        do {
            let encoder = JSONEncoder()
            encoder.dateEncodingStrategy = .iso8601
            request.httpBody = try encoder.encode(payload)
            _ = try await URLSession.shared.data(for: request)
        } catch {
            return
        }
    }
}

private enum AppContext {
    static var bundleIdentifier: String {
        Bundle.main.bundleIdentifier ?? "unknown.bundle"
    }

    static var appVersion: String {
        Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0"
    }

    static var buildNumber: String {
        Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "0"
    }
}

private struct AnalyticsPayload: Codable {
    let appIdentifier: String
    let appVersion: String
    let buildNumber: String
    let event: AnalyticsEvent
}
