import XCTest
@testable import ByteLystPlatformSDK

final class BLTelemetryClientTests: XCTestCase {

    private func makeClient() -> BLTelemetryClient {
        let config = BLPlatformConfig(
            productId: "testapp",
            baseURL: "http://localhost:4003",
            bundleId: "com.bytelyst.test"
        )
        let platformClient = BLPlatformClient(config: config)
        return BLTelemetryClient(config: config, client: platformClient)
    }

    func testInstallIdIsStable() {
        let client = makeClient()
        let id1 = client.getInstallId()
        let id2 = client.getInstallId()
        XCTAssertEqual(id1, id2)
        XCTAssertFalse(id1.isEmpty)
    }

    func testSessionIdIsNotEmpty() {
        let client = makeClient()
        XCTAssertFalse(client.getSessionId().isEmpty)
    }

    func testStartGeneratesNewSessionId() {
        let client = makeClient()
        let sessionBefore = client.getSessionId()
        client.start()
        let sessionAfter = client.getSessionId()
        // start() rotates session ID
        XCTAssertNotEqual(sessionBefore, sessionAfter)
        client.stop()
    }

    func testStopDoesNotCrash() {
        let client = makeClient()
        client.stop() // Stop without start
        client.start()
        client.stop()
        client.stop() // Double stop
    }

    func testTrackEventDoesNotCrash() {
        let client = makeClient()
        client.trackEvent("info", module: "test", name: "unit_test")
        client.trackEvent("error", module: "test", name: "fail", message: "test error")
        client.trackEvent("info", module: "test", name: "tagged", tags: ["key": "value"])
        client.trackEvent("info", module: "test", name: "measured", metrics: ["duration": 1.5])
    }

    func testTrackScreenDoesNotCrash() {
        let client = makeClient()
        client.trackScreen("home")
        client.trackScreen("settings")
    }

    func testFlushDoesNotCrashWhenEmpty() {
        let client = makeClient()
        client.flush() // Empty queue
    }
}
