//
//  LocationProviderTests.swift
//  suixinkanTests
//

import CoreLocation
import XCTest
@testable import suixinkan

/// 定位协议与 ViewModel 注入测试。
final class LocationProviderTests: XCTestCase {

    private var defaults: UserDefaults!
    private var appStore: AppStore!

    override func setUp() {
        super.setUp()
        defaults = UserDefaults(suiteName: "LocationProviderTests")!
        defaults.removePersistentDomain(forName: "LocationProviderTests")
        appStore = AppStore(defaults: defaults)
        appStore.session.configureTestAccount()
    }

    func testScenicSelectionUsesInjectedProviderSnapshot() async {
        let mock = MockLocationProvider()
        mock.snapshot = HomeLocationSnapshot(latitude: 30.2, longitude: 120.1, address: "杭州")
        appStore.permissions.saveRoleScenicList([
            ScenicInfo(id: 1, name: "西湖", status: 1, location: ScenicLocationInfo(lng: 120.1, lat: 30.2, address: "杭州"), coverImg: nil),
        ])

        let viewModel = ScenicSelectionViewModel(appStore: appStore, locationProvider: mock)
        var message: String?
        viewModel.onShowMessage = { message = $0 }

        await viewModel.startLocation()

        XCTAssertEqual(viewModel.currentLocationText, "杭州")
        XCTAssertNil(message)
    }

    func testLocationReportViewModelUsesInjectedReverseGeocode() async {
        let mock = MockLocationProvider()
        mock.reverseGeocodeResult = "标记地址"
        let viewModel = LocationReportViewModel(locationProvider: mock)

        viewModel.toggleMarking()
        viewModel.setMarkerLocation(latitude: 30.1, longitude: 120.2)
        try? await Task.sleep(nanoseconds: 200_000_000)

        XCTAssertEqual(viewModel.markerAddress, "标记地址")
    }

    func testMockLocationProviderCoordinate() async throws {
        let mock = MockLocationProvider()
        mock.coordinate = CLLocationCoordinate2D(latitude: 31.0, longitude: 121.0)

        let coordinate = try await mock.requestCoordinate()
        XCTAssertEqual(coordinate.latitude, 31.0, accuracy: 0.0001)
        XCTAssertEqual(coordinate.longitude, 121.0, accuracy: 0.0001)
    }
}
