import Foundation
import OSLog

private let logger = Logger(subsystem: "nahbar", category: "TourSeenStore")

// MARK: - TourSeenStore

/// Persists which tour IDs have been completed and the last-seen app version.
/// Injected into TourCoordinator to keep it testable.
final class TourSeenStore {

    private let defaults: UserDefaults
    private let seenIDsKey = "nahbar.tour.seenIDs"
    private let lastSeenVersionKey = "nahbar.tour.lastSeenAppVersion"

    init(defaults: UserDefaults = .standard) {
        self.defaults = defaults
    }

    // MARK: Seen IDs

    func hasSeen(_ id: TourID) -> Bool {
        seenIDs.contains(id)
    }

    func markSeen(_ id: TourID) {
        var ids = seenIDs
        ids.insert(id)
        seenIDs = ids
        logger.info("Tour als gesehen markiert: \(id.rawValue)")
    }

    func reset() {
        defaults.removeObject(forKey: seenIDsKey)
        defaults.removeObject(forKey: lastSeenVersionKey)
        logger.info("TourSeenStore zurückgesetzt")
    }

    // MARK: Last Seen App Version

    var lastSeenAppVersion: String? {
        get { defaults.string(forKey: lastSeenVersionKey) }
        set {
            if let newValue {
                defaults.set(newValue, forKey: lastSeenVersionKey)
            } else {
                defaults.removeObject(forKey: lastSeenVersionKey)
            }
        }
    }

    // MARK: Private

    private var seenIDs: Set<TourID> {
        get {
            guard let data = defaults.data(forKey: seenIDsKey),
                  let ids = try? JSONDecoder().decode(Set<TourID>.self, from: data)
            else { return [] }
            return ids
        }
        set {
            guard let data = try? JSONEncoder().encode(newValue) else { return }
            defaults.set(data, forKey: seenIDsKey)
        }
    }
}
