//
//  OnboardingDataDataManager.swift
//  Reflect (iOS)
//
//  Created by Trey Tartt on 2/18/22.
//

import Foundation
import WidgetKit

final class OnboardingDataDataManager: ObservableObject {
    static let shared = OnboardingDataDataManager()

    @Published public private(set) var savedOnboardingData = UserDefaultsStore.getOnboarding()

    public func updateOnboardingData(onboardingData: OnboardingData) {
        let onboardingData = UserDefaultsStore.saveOnboarding(onboardingData: onboardingData)
        savedOnboardingData = onboardingData
        LocalNotification.scheduleReminder(atTime: onboardingData.date)

        // Update Live Activity schedule when rating time changes
        Task { @MainActor in
            LiveActivityScheduler.shared.onRatingTimeUpdated()
        }

        // Force sync UserDefaults to app group before reloading widgets
        GroupUserDefaults.groupDefaults.synchronize()

        // Reload widgets so they show the correct view for new time
        WidgetCenter.shared.reloadAllTimelines()
    }
}
