//
//  LoginViewModelTests.swift
//  suixinkanTests
//
//  Created by Codex on 2026/6/20.
//

import XCTest
@testable import suixinkan

@MainActor
/// 登录页 ViewModel 测试，覆盖手机号规范化、表单校验和偏好恢复。
final class LoginViewModelTests: XCTestCase {
    /// 测试 +86 手机号会被规范化为 11 位国内手机号。
    func testNormalizeUsernameCountryCodeRemovesChinaPrefix() {
        let viewModel = LoginViewModel()
        viewModel.username = "+86 186 5185 7230"

        viewModel.normalizeUsernameCountryCodeIfNeeded()

        XCTAssertEqual(viewModel.username, "18651857230")
        XCTAssertEqual(viewModel.normalizedUsername, "18651857230")
        XCTAssertTrue(viewModel.isValidPhone)
    }

    /// 测试未勾选协议时登录校验返回隐私协议错误。
    func testValidateForLoginRequiresPrivacyAgreement() {
        let viewModel = LoginViewModel()
        viewModel.username = "18651857230"
        viewModel.password = "secret123"
        viewModel.privacyChecked = false

        XCTAssertEqual(viewModel.validateForLogin(), .privacyUnchecked)
    }

    /// 测试登录偏好只恢复手机号和协议状态，不恢复密码。
    func testApplyPreferencesRestoresUsernameAndPrivacyOnly() {
        let viewModel = LoginViewModel()
        viewModel.password = "manual-password"

        viewModel.applyPreferences(
            LoginPreferences(
                lastUsername: "18651857230",
                privacyAgreementAccepted: true
            )
        )

        XCTAssertEqual(viewModel.username, "18651857230")
        XCTAssertTrue(viewModel.privacyChecked)
        XCTAssertEqual(viewModel.password, "manual-password")
    }
}
