//
// WorkoutLauncher.swift
// Workouts
//
// Copyright 2025 Rouslan Zenetl. All Rights Reserved.
//

import Foundation
import HealthKit

/// Launches the companion Watch app into a workout when a session starts on the phone.
///
/// An iPhone app can't foreground its Watch app on its own — the only sanctioned path
/// is HealthKit's `startWatchApp(toHandle:)`, which hands watchOS a workout
/// configuration and brings the Watch app up to run a matching `HKWorkoutSession`.
/// Calling it requires authorization to *share* workouts first.
@MainActor
final class WorkoutLauncher {
    private let healthStore = HKHealthStore()

    /// Configuration handed to watchOS; the watch starts a session with the same
    /// shape (see `WorkoutSessionManager`). The activity type comes from the routine so
    /// the saved Health workout is categorized correctly.
    static func makeConfiguration(activityType: HKWorkoutActivityType) -> HKWorkoutConfiguration {
        let configuration = HKWorkoutConfiguration()
        configuration.activityType = activityType
        configuration.locationType = .indoor
        return configuration
    }

    /// Ask watchOS to launch the Watch app into the workout. Best-effort: no-ops where
    /// HealthKit is unavailable (e.g. iPad without it) and silently tolerates a missing
    /// or unreachable paired watch. Requests the workout-share scope that
    /// `startWatchApp(toHandle:)` itself requires (also enough for a legacy Health delete).
    func launchWatchWorkout(activityType: HKWorkoutActivityType) {
        guard HKHealthStore.isHealthDataAvailable() else { return }
        Task {
            try? await healthStore.requestAuthorization(toShare: [.workoutType()], read: [])
            try? await healthStore.startWatchApp(toHandle: Self.makeConfiguration(activityType: activityType))
        }
    }
}
