import Foundation

// MARK: - Timer state persistence across relaunches

enum TimerPersistence {
    private static let keyRemaining = "pommedoro.persistedRemainingSeconds"
    private static let keyPaused = "pommedoro.persistedIsPaused"
    private static let keyIntervalStart = "pommedoro.persistedIntervalStart"

    private static let defaults = UserDefaults.standard

    /// Save work timer state. Call on terminate. Only saves when remainingSeconds > 0.
    static func save(remainingSeconds: Int, isPaused: Bool, intervalStartDate: Date?) {
        guard remainingSeconds > 0 else {
            clear()
            return
        }
        defaults.set(remainingSeconds, forKey: keyRemaining)
        defaults.set(isPaused, forKey: keyPaused)
        defaults.set(intervalStartDate?.timeIntervalSince1970, forKey: keyIntervalStart)
    }

    /// Restore saved state. Returns nil if nothing valid saved (e.g. timer had finished).
    static func restore() -> (remainingSeconds: Int, isPaused: Bool, intervalStartDate: Date?)? {
        let remaining = defaults.integer(forKey: keyRemaining)
        guard remaining > 0 else {
            clear()
            return nil
        }
        let paused = defaults.bool(forKey: keyPaused)
        let start: Date? = {
            let t = defaults.double(forKey: keyIntervalStart)
            return t > 0 ? Date(timeIntervalSince1970: t) : nil
        }()
        return (remainingSeconds: remaining, isPaused: paused, intervalStartDate: start)
    }

    static func clear() {
        defaults.removeObject(forKey: keyRemaining)
        defaults.removeObject(forKey: keyPaused)
        defaults.removeObject(forKey: keyIntervalStart)
    }
}
