//
//  HealthManager.swift
//  anniversary_Project
//
//  Created by 忆海16 on 2024/7/10.
//

import Foundation
import HealthKit

class HealthManager {
    let healthStore = HKHealthStore()
    
    func requestAuthorization(completion: @escaping (Bool, Error?) -> Void) {
        guard HKHealthStore.isHealthDataAvailable() else {
            completion(false, nil)
            return
        }
        
        let waterType = HKObjectType.quantityType(forIdentifier: .dietaryWater)!
        
        healthStore.requestAuthorization(toShare: [waterType], read: [waterType]) { (success, error) in
            completion(success, error)
        }
    }
    
    func saveWaterIntake(waterQuantity: Double, date: Date) {
        guard let waterType = HKObjectType.quantityType(forIdentifier: .dietaryWater) else {
            return
        }
        
        let waterQuantityUnit = HKUnit.liter()
        let waterQuantitySample = HKQuantity(unit: waterQuantityUnit, doubleValue: waterQuantity)
        let waterSample = HKQuantitySample(type: waterType, quantity: waterQuantitySample, start: date, end: date)
        
        healthStore.save(waterSample) { (success, error) in
            if success {
                print("Successfully saved water intake to HealthKit")
            } else if let error = error {
                print("Error saving water intake to HealthKit: \(error.localizedDescription)")
            }
        }
    }
}
