import Foundation
import SwiftData

@Observable
final class DashboardViewModel {
    var isRequestingAuth = false
    var isCreatingSnapshot = false
    var authError: String?
    var snapshotError: String?

    private let healthKit = HealthKitService.shared
    private let diffService = SnapshotDiffService.shared

    func requestAuthorization() async {
        isRequestingAuth = true
        authError = nil
        defer { isRequestingAuth = false }
        do {
            try await healthKit.requestAuthorization()
        } catch {
            authError = error.localizedDescription
        }
    }

    func createSnapshot(context: ModelContext, selectedTypeIDs: Set<String>) async {
        isCreatingSnapshot = true
        snapshotError = nil
        defer { isCreatingSnapshot = false }
        do {
            _ = try await healthKit.createSnapshot(in: context, selectedTypeIDs: selectedTypeIDs)
        } catch {
            snapshotError = error.localizedDescription
        }
    }

    func totalChanges(latest: HealthSnapshot, previous: HealthSnapshot) -> Int {
        diffService.totalAbsoluteChange(current: latest, baseline: previous)
    }
}
