import XCTest
@testable import ByteLystPlatformSDK

final class ByteLystPlatformTests: XCTestCase {

    private func makeConfig() -> BLPlatformConfig {
        BLPlatformConfig(
            productId: "testapp",
            baseURL: "http://localhost:4003/api",
            platform: "ios",
            channel: "native",
            bundleId: "com.bytelyst.test"
        )
    }

    func testInitCreatesAllServices() {
        let platform = ByteLystPlatform(config: makeConfig())
        XCTAssertEqual(platform.config.productId, "testapp")
        XCTAssertNotNil(platform.client)
        XCTAssertNotNil(platform.telemetry)
        XCTAssertNotNil(platform.flags)
        XCTAssertNotNil(platform.killSwitch)
        XCTAssertNotNil(platform.crashReporter)
        XCTAssertNotNil(platform.keychain)
        XCTAssertNotNil(platform.auditLog)
        XCTAssertNotNil(platform.auth)
    }

    func testStartSetsIsStarted() {
        let platform = ByteLystPlatform(config: makeConfig())
        XCTAssertFalse(platform.isStarted)
        platform.start()
        XCTAssertTrue(platform.isStarted)
    }

    func testStopClearsIsStarted() {
        let platform = ByteLystPlatform(config: makeConfig())
        platform.start()
        XCTAssertTrue(platform.isStarted)
        platform.stop()
        XCTAssertFalse(platform.isStarted)
    }

    func testDoubleStartIsIdempotent() {
        let platform = ByteLystPlatform(config: makeConfig())
        platform.start()
        platform.start() // Should not crash or double-start
        XCTAssertTrue(platform.isStarted)
        platform.stop()
    }

    func testDoubleStopIsIdempotent() {
        let platform = ByteLystPlatform(config: makeConfig())
        platform.start()
        platform.stop()
        platform.stop() // Should not crash
        XCTAssertFalse(platform.isStarted)
    }

    func testKeychainAccessor() {
        let accessor = BLKeychainAccessor(service: "com.bytelyst.test.accessor")
        accessor.save(key: "test_key", value: "hello")
        XCTAssertEqual(accessor.read(key: "test_key"), "hello")
        accessor.delete(key: "test_key")
        XCTAssertNil(accessor.read(key: "test_key"))
    }
}
