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

import XCTest
@testable import suixinkan

/// 本地缓存 Store 测试，覆盖 UserDefaults 中的偏好和账号快照。
final class StorageTests: XCTestCase {
    /// 测试 AppPreferencesStore 能保存并读取上次登录手机号和协议状态。
    func testAppPreferencesStorePersistsLoginPreferences() {
        let defaults = makeIsolatedDefaults()
        let store = AppPreferencesStore(defaults: defaults)

        store.saveLastLoginUsername(" 18651857230 ")
        store.savePrivacyAgreementAccepted(true)

        XCTAssertEqual(store.loadLastLoginUsername(), "18651857230")
        XCTAssertTrue(store.loadPrivacyAgreementAccepted())
    }

    /// 测试账号快照能保存并恢复账号资料、业务作用域和当前选择。
    func testAccountSnapshotStorePersistsAccountContextSnapshot() {
        let defaults = makeIsolatedDefaults()
        let store = AccountSnapshotStore(defaults: defaults)
        let snapshot = AccountSnapshot(
            profile: AccountProfile(
                userId: "101",
                displayName: "测试账号",
                phone: "18651857230",
                avatarURL: "https://cdn.example.com/avatar.jpg"
            ),
            accountType: "store_user",
            businessUserId: 101,
            scenicScopes: [
                BusinessScope(id: 88, name: "东门景区", kind: .scenic)
            ],
            storeScopes: [
                BusinessScope(id: 66, name: "东门门店", kind: .store)
            ],
            currentScenicId: 88,
            currentStoreId: 66
        )

        store.save(snapshot)

        XCTAssertEqual(store.load(), snapshot)
    }

    /// 创建独立 UserDefaults，避免测试污染真实 App 偏好。
    private func makeIsolatedDefaults() -> UserDefaults {
        let suiteName = "suixinkan.tests.\(UUID().uuidString)"
        let defaults = UserDefaults(suiteName: suiteName)!
        defaults.removePersistentDomain(forName: suiteName)
        return defaults
    }
}
