//
//  AppConfigTests.swift
//  suixinkanTests
//
//  Created by Codex on 2026/6/29.
//

import XCTest
@testable import suixinkan

@MainActor
/// App 配置接口测试，覆盖 API 请求路径和登录页配置加载行为。
final class AppConfigTests: XCTestCase {
    /// 测试 App 配置接口使用正确路径并解析 enable_register 字段。
    func testAppConfigAPIRequestsConfigEndpoint() async throws {
        let response = """
        {
          "code": 100000,
          "msg": "success",
          "data": {
            "enable_register": true
          }
        }
        """.data(using: .utf8)!
        let session = AppConfigURLSession(responses: [response])
        let api = AppConfigAPI(client: APIClient(session: session))

        let config = try await api.fetchAppConfig()

        XCTAssertTrue(config.enableRegister)
        let request = try XCTUnwrap(session.requests.first)
        XCTAssertEqual(request.httpMethod, "GET")
        XCTAssertEqual(request.url?.path, "/api/app/config")
    }

    /// 测试登录页加载 App 配置成功时会更新 enableRegister。
    func testLoginViewModelLoadAppConfigUpdatesEnableRegister() async throws {
        let response = """
        {
          "code": 100000,
          "msg": "success",
          "data": {
            "enable_register": true
          }
        }
        """.data(using: .utf8)!
        let session = AppConfigURLSession(responses: [response])
        let api = AppConfigAPI(client: APIClient(session: session))
        let viewModel = LoginViewModel()

        await viewModel.loadAppConfig(appConfigAPI: api)

        XCTAssertTrue(viewModel.enableRegister)
    }

    /// 测试登录页加载 App 配置失败时保持默认值。
    func testLoginViewModelLoadAppConfigKeepsDefaultOnFailure() async {
        let session = AppConfigURLSession(responses: [Data()])
        let api = AppConfigAPI(client: APIClient(session: session))
        let viewModel = LoginViewModel()

        await viewModel.loadAppConfig(appConfigAPI: api)

        XCTAssertFalse(viewModel.enableRegister)
    }
}

/// App 配置测试用 URLSession 替身，按顺序返回预设响应。
private final class AppConfigURLSession: URLSessionProtocol {
    private var responses: [Data]
    private(set) var requests: [URLRequest] = []

    /// 初始化顺序响应。
    init(responses: [Data]) {
        self.responses = responses
    }

    /// 记录请求并返回下一份响应。
    func data(for request: URLRequest) async throws -> (Data, URLResponse) {
        requests.append(request)
        let data = responses.isEmpty ? Data() : responses.removeFirst()
        return (
            data,
            HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
        )
    }
}
