//
//  LocationProviding.swift
//  suixinkan
//

import CoreLocation
import Foundation

/// 位置采集结果。
struct HomeLocationSnapshot: Sendable, Equatable {
    let latitude: Double
    let longitude: Double
    let address: String
}

/// 定位服务协议，便于 ViewModel 注入与单元测试 mock。
protocol LocationProviding: Sendable {
    /// 按指定精度请求当前坐标与地址。
    @MainActor
    func requestSnapshot(desiredAccuracy: CLLocationAccuracy) async throws -> HomeLocationSnapshot
    /// 按指定精度请求当前坐标。
    @MainActor
    func requestCoordinate(desiredAccuracy: CLLocationAccuracy) async throws -> CLLocationCoordinate2D
    /// 逆地理编码。
    @MainActor
    func reverseGeocode(latitude: Double, longitude: Double) async -> String
}

extension LocationProviding {
    /// 请求当前坐标与地址，默认使用最高精度以保持既有业务行为。
    @MainActor
    func requestSnapshot() async throws -> HomeLocationSnapshot {
        try await requestSnapshot(desiredAccuracy: kCLLocationAccuracyBest)
    }

    /// 请求当前坐标，默认使用最高精度以保持既有业务行为。
    @MainActor
    func requestCoordinate() async throws -> CLLocationCoordinate2D {
        try await requestCoordinate(desiredAccuracy: kCLLocationAccuracyBest)
    }
}

/// 定位错误。
enum LocationProviderError: LocalizedError, Equatable {
    case privacyNotAccepted
    case permissionDenied
    case locationFailed

    var errorDescription: String? {
        switch self {
        case .privacyNotAccepted:
            "请先阅读并同意隐私政策"
        case .permissionDenied:
            "需要定位权限才能使用此功能"
        case .locationFailed:
            "定位失败，请稍后重试"
        }
    }
}

/// 订单核销场景定位错误，保持原有提示文案。
enum OrderLocationError: LocalizedError {
    case permissionDenied

    var errorDescription: String? {
        switch self {
        case .permissionDenied:
            "缺少定位权限，功能无法进行"
        }
    }
}
