import Foundation

struct LocalOperationLog: Codable, Equatable, Identifiable, Sendable {
    var id: UUID = UUID()
    var timestamp: Date = Date.now
    var operationType: String
    var affectedSnapshotIDs: [String] = []
    var summary: String
    var operationDeviceID: String
    var operationAppBuildVersion: String

    init(operationType: String, summary: String, deviceID: String, appBuildVersion: String) {
        self.operationType = operationType
        self.summary = summary
        self.operationDeviceID = deviceID
        self.operationAppBuildVersion = appBuildVersion
    }
}

enum LocalOperationLogStore {
    private static let key = "hp_localOperationLogs"
    private static let maximumEntries = 200

    static func allLogs() -> [LocalOperationLog] {
        load().sorted { $0.timestamp > $1.timestamp }
    }

    static func append(_ log: LocalOperationLog) {
        var logs = load()
        logs.append(log)
        if logs.count > maximumEntries {
            logs = Array(logs.suffix(maximumEntries))
        }
        save(logs)
    }

    static func removeAll() {
        UserDefaults.standard.removeObject(forKey: key)
    }

    private static func load() -> [LocalOperationLog] {
        guard let data = UserDefaults.standard.data(forKey: key) else { return [] }
        return (try? JSONDecoder().decode([LocalOperationLog].self, from: data)) ?? []
    }

    private static func save(_ logs: [LocalOperationLog]) {
        UserDefaults.standard.set(try? JSONEncoder().encode(logs), forKey: key)
    }
}
