//
//  DataStateManager.swift

import Foundation

/// Manages the overall data state timestamp for sync purposes
class DataStateManager {

    private let userDefaults = UserDefaults.standard

    private enum Keys {
        static let lastModified = "ascently_data_last_modified"
        static let initialized = "ascently_data_state_initialized"
    }

    static let shared = DataStateManager()

    private init() {
        // Initialize with current timestamp if this is the first time
        if !isInitialized() {
            AppLogger.info("DataStateManager: First time initialization", tag: "DataState")
            // Set initial timestamp to a very old date so server data will be considered newer
            let epochTime = "1970-01-01T00:00:00.000Z"
            userDefaults.set(epochTime, forKey: Keys.lastModified)
            markAsInitialized()
            AppLogger.info(
                "DataStateManager initialized with epoch timestamp: \(epochTime)", tag: "DataState")
        } else {
            AppLogger.info(
                "DataStateManager: Already initialized, current timestamp: \(getLastModified())",
                tag: "DataState")
        }
    }

    /// Updates the data state timestamp to the current time. Call this whenever any data is modified
    /// (create, update, delete).
    func updateDataState() {
        let now = ISO8601DateFormatter().string(from: Date())
        userDefaults.set(now, forKey: Keys.lastModified)
        AppLogger.info("iOS Data state updated to: \(now)", tag: "DataState")
    }

    func getLastModified() -> String {
        if let storedTimestamp = userDefaults.string(forKey: Keys.lastModified) {
            AppLogger.debug(
                "iOS DataStateManager returning stored timestamp: \(storedTimestamp)",
                tag: "DataState")
            return storedTimestamp
        }

        let epochTime = "1970-01-01T00:00:00.000Z"
        AppLogger.warning(
            "No data state timestamp found - returning epoch time: \(epochTime)", tag: "DataState")
        return epochTime
    }

    func setLastModified(_ timestamp: String) {
        userDefaults.set(timestamp, forKey: Keys.lastModified)
        AppLogger.info("Data state set to: \(timestamp)", tag: "DataState")
    }

    func reset() {
        userDefaults.removeObject(forKey: Keys.lastModified)
        userDefaults.removeObject(forKey: Keys.initialized)
        AppLogger.info("Data state reset", tag: "DataState")
    }

    private func isInitialized() -> Bool {
        return userDefaults.bool(forKey: Keys.initialized)
    }

    private func markAsInitialized() {
        userDefaults.set(true, forKey: Keys.initialized)
    }

    func getDebugInfo() -> String {
        return "DataState(lastModified=\(getLastModified()), initialized=\(isInitialized()))"
    }
}
