import Foundation
import Testing

@testable import NucleicCore

@Suite struct PushRelayTests {
    @Test func disabledByDefault() {
        // No toggle, no env → the push path stays entirely off.
        #expect(PushRelayConfig.resolve(
            environment: [:], defaults: UserDefaults(suiteName: "PushRelayTests-off")!) == nil)
    }

    @Test func toggleEnablesWithProductionDefaults() {
        let defaults = UserDefaults(suiteName: "PushRelayTests-toggle")!
        defaults.set(true, forKey: "nucleic.relay.enabled")
        defer { defaults.removeObject(forKey: "nucleic.relay.enabled") }
        let config = PushRelayConfig.resolve(environment: [:], defaults: defaults)
        // A distributed build needs exactly the toggle: production relay, production APNS.
        #expect(config?.baseURL == PushRelayConfig.defaultBaseURL)
        #expect(config?.apnsEnv == "production")
    }

    @Test func envOverridesEnableAndRedirectForDev() {
        let defaults = UserDefaults(suiteName: "PushRelayTests-dev")!
        let config = PushRelayConfig.resolve(
            environment: [
                "NUCLEIC_RELAY_ENABLED": "1",
                "NUCLEIC_RELAY_URL": "http://localhost:8787",
                "NUCLEIC_APNS_ENV": "sandbox",
            ], defaults: defaults)
        #expect(config?.baseURL.absoluteString == "http://localhost:8787")
        #expect(config?.apnsEnv == "sandbox")
    }

    @Test func devDefaultsKeysBackTheSettingsFields() {
        let defaults = UserDefaults(suiteName: "PushRelayTests-devdefaults")!
        defaults.set(true, forKey: "nucleic.relay.enabled")
        defaults.set("http://localhost:8787", forKey: "NUCLEIC_RELAY_URL")
        defaults.set("sandbox", forKey: "NUCLEIC_APNS_ENV")
        defer {
            defaults.removeObject(forKey: "nucleic.relay.enabled")
            defaults.removeObject(forKey: "NUCLEIC_RELAY_URL")
            defaults.removeObject(forKey: "NUCLEIC_APNS_ENV")
        }
        let config = PushRelayConfig.resolve(environment: [:], defaults: defaults)
        #expect(config?.baseURL.absoluteString == "http://localhost:8787")
        #expect(config?.apnsEnv == "sandbox")
    }

    @Test func credentialBearerJoinsIDAndSecret() {
        let credential = RelayHostCredential(hostID: "host-1", secret: "s3cret")
        #expect(credential.bearer == "host-1.s3cret")
    }
}
