import Foundation
import Combine

/// Throttled progress persistence for Study sessions.
@MainActor
final class ProgressSaver: ObservableObject {
    private var lastSave = Date.distantPast
    /// Soft throttle for high-frequency gestures (drag / scrub).
    private let minimumInterval: TimeInterval = 1.5

    func save(
        session: StudySession,
        mediaTime: Double,
        pdfPage: Int,
        splitRatio: Double,
        orientation: SplitOrientation,
        force: Bool = false,
        store: LibraryStore
    ) {
        let now = Date()
        if !force && now.timeIntervalSince(lastSave) < minimumInterval {
            return
        }
        session.mediaTime = mediaTime
        session.pdfPage = max(1, pdfPage)
        session.splitRatio = min(0.85, max(0.15, splitRatio))
        session.orientation = orientation
        session.updatedAt = now
        try? store.modelContext.save()
        lastSave = now
    }
}
