import Foundation
import Testing
@testable import IrdP2PSignaling
@Suite struct TurnCredentialsTests {
let creds = #"{"username":"1787000000:app:nonce","credential":"c3Vy","ttl":3600,"urls":["stun:p1.ap2p.ro:3478","turn:p1.ap2p.ro:3478?transport=udp"]}"#
@Test func fetchesCachesAndRenewsBeforeExpiry() async {
let http = FakeHTTP { _ in json(200, self.creds) }
let clock = TestClock()
let cache = IceServerCache(url: URL(string: "https://app.example.test/turn-credentials")!, origin: "https://o.example", http: http, clock: clock)
let c = await cache.configuration()
#expect(c.servers == [IceServer(urls: ["stun:p1.ap2p.ro:3478", "turn:p1.ap2p.ro:3478?transport=udp"], username: "1787000000:app:nonce", credential: "c3Vy")])
#expect(http.last?.value(forHTTPHeaderField: "Origin") == "https://o.example")
_ = await cache.configuration()
#expect(http.count == 1)
clock.advance(by: .seconds(3600 - 301))
_ = await cache.configuration()
#expect(http.count == 1)
clock.advance(by: .seconds(2))
_ = await cache.configuration()
#expect(http.count == 2)
}
@Test func failureDegradesToEmptyAndRetriesAfter30s() async {
let http = FakeHTTP { _ in json(403, #"{"error":"origin_not_allowed"}"#) }
let clock = TestClock()
let cache = IceServerCache(url: URL(string: "https://app.example.test/turn-credentials")!, origin: nil, http: http, clock: clock, relayOnly: true)
let c = await cache.configuration()
#expect(c.servers.isEmpty && c.relayOnly)
_ = await cache.configuration()
#expect(http.count == 1)
clock.advance(by: .seconds(31))
_ = await cache.configuration()
#expect(http.count == 2)
}
@Test func oneInFlightFetchIsShared() async {
let http = FakeHTTP { _ in try? await Task.sleep(for: .milliseconds(50)); return json(200, self.creds) }
let cache = IceServerCache(url: URL(string: "https://app.example.test/turn-credentials")!, origin: nil, http: http, clock: TestClock())
async let a = cache.configuration()
async let b = cache.configuration()
_ = await (a, b)
#expect(http.count == 1)
}
@Test func noURLMeansNoServers() async {
let http = FakeHTTP()
let cache = IceServerCache(url: nil, origin: nil, http: http, clock: TestClock())
#expect(await cache.configuration() == .none)
#expect(http.count == 0)
}
}