//
//  ProfileViewModelTests.swift
//  suixinkanTests
//

import XCTest
@testable import suixinkan

@MainActor
/// 个人信息页 ViewModel 测试。
final class ProfileViewModelTests: XCTestCase {

    override func setUp() {
        super.setUp()
        AppStore.shared.logout()
        AppStore.shared.session.configureTestAccount(userId: "profile-user")
    }

    override func tearDown() {
        AppStore.shared.logout()
        super.tearDown()
    }

    func testDisplayNicknameUsesFallbackWhenEmpty() {
        let viewModel = ProfileViewModel()
        XCTAssertEqual(viewModel.displayNickname, "未设置昵称")
    }

    func testShowPhotographerFieldsWhenRoleCodeIsPhotographer() {
        AppStore.shared.session.roleCode = AppRoleCode.photographer.rawValue
        let viewModel = ProfileViewModel()
        XCTAssertTrue(viewModel.showPhotographerFields)
        AppStore.shared.session.roleCode = ""
    }

    func testMaskCardNumberShowsLastFourDigits() {
        XCTAssertEqual(
            ProfileViewModel.maskCardNumber("6222021234567890"),
            "**** **** **** 7890"
        )
    }

    func testUpdatePasswordRejectsShortPassword() async {
        let session = MockURLSession(responses: [])
        let api = ProfileAPI(client: APIClient(environment: .testing, session: session))
        let viewModel = ProfileViewModel()

        do {
            try await viewModel.updatePassword("12345", api: api)
            XCTFail("短密码应抛出校验错误")
        } catch {
            guard let validationError = error as? ProfileValidationError else {
                return XCTFail("期望 ProfileValidationError，实际为 \(error)")
            }
            XCTAssertEqual(validationError, .shortPassword)
        }
    }

    func testAccountTypeLabelForStoreAccount() {
        AppStore.shared.session.accountType = .storeUser
        let viewModel = ProfileViewModel()
        XCTAssertEqual(viewModel.accountTypeLabel, "门店账号")
        XCTAssertTrue(viewModel.isStoreAccount)
        AppStore.shared.session.accountType = .unknown("")
    }

    func testAccountTypeLabelForScenicAccount() {
        AppStore.shared.session.accountType = .scenicUser
        let viewModel = ProfileViewModel()
        XCTAssertEqual(viewModel.accountTypeLabel, "景区账号")
        XCTAssertFalse(viewModel.isStoreAccount)
        AppStore.shared.session.accountType = .unknown("")
    }

    func testApplyLocalProfileUpdateSyncsNicknameAndAvatar() {
        AppStore.shared.session.userName = "全局昵称"
        AppStore.shared.session.avatar = "https://cdn.example.com/new.jpg"

        let viewModel = ProfileViewModel()
        viewModel.applyLocalProfileUpdate()

        XCTAssertEqual(viewModel.displayNickname, "全局昵称")
        XCTAssertEqual(viewModel.displayAvatarURL, "https://cdn.example.com/new.jpg")

        AppStore.shared.session.userName = ""
        AppStore.shared.session.avatar = ""
    }
}
