import Foundation
import Testing
@testable import TestSupport

@Suite("FakeHTTPTransport")
struct FakeHTTPTransportTests {
    private static let originValue = "http://192.168.1.5:3000"

    @Test("replays queued responses per URL/method, records requests with headers, and fails loudly when unqueued")
    func replaysQueuedResponsesAndRecordsRequests() async throws {
        // Arrange
        let transport = FakeHTTPTransport()
        let listURL = try #require(URL(string: "http://192.168.1.5:3000/live-sessions"))
        let unqueuedURL = try #require(URL(string: "http://192.168.1.5:3000/other"))
        let body = Data("[]".utf8)
        await transport.queueSuccess(url: listURL, body: body)

        var request = URLRequest(url: listURL)
        request.httpMethod = "GET"
        request.setValue(Self.originValue, forHTTPHeaderField: "Origin")

        // Act
        let (data, response) = try await transport.send(request)

        // Assert: the queued response came back for that URL/method.
        #expect(data == body)
        #expect(response.statusCode == FakeHTTPTransport.defaultOKStatus)
        #expect(response.url == listURL)

        // Assert: the request was recorded verbatim, headers included
        // (this is what lets APIClient tests assert Origin-iff-G, plan §3.4).
        let recorded = await transport.recordedRequests
        #expect(recorded.count == 1)
        #expect(recorded.first?.url == listURL)
        #expect(recorded.first?.value(forHTTPHeaderField: "Origin") == Self.originValue)

        // Assert: an unqueued route throws an explicit, identifying error.
        await #expect(throws: FakeHTTPTransportError.noQueuedResponse(method: "GET", url: unqueuedURL)) {
            _ = try await transport.send(URLRequest(url: unqueuedURL))
        }
    }
}
