import Foundation
import Observation
import Bedrock

@MainActor
@Observable
final class SettingsStore: CloudSyncable {
    @ObservationIgnored private let cloudSync = CloudSyncManager<AppSettingsData>()

    var hapticsEnabled: Bool {
        get { cloudSync.data.hapticsEnabled }
        set { update { $0.hapticsEnabled = newValue } }
    }

    var soundEnabled: Bool {
        get { cloudSync.data.soundEnabled }
        set { update { $0.soundEnabled = newValue } }
    }

    var iCloudAvailable: Bool { cloudSync.iCloudAvailable }

    var iCloudEnabled: Bool {
        get { cloudSync.iCloudEnabled }
        set { cloudSync.iCloudEnabled = newValue }
    }

    var lastSyncDate: Date? { cloudSync.lastSyncDate }
    var syncStatus: String { cloudSync.syncStatus }
    var hasCompletedInitialSync: Bool { cloudSync.hasCompletedInitialSync }

    func forceSync() {
        cloudSync.sync()
    }

    func refresh() {
        cloudSync.sync()
    }

    private func update(_ transform: (inout AppSettingsData) -> Void) {
        cloudSync.update { data in
            transform(&data)
        }
    }
}

extension SettingsStore {
    static var preview: SettingsStore {
        SettingsStore()
    }
}
