import Foundation
import SwiftData

@Model final class OperationLog {
    @Attribute(.unique) var id: UUID
    @Attribute var timestamp: Date
    @Attribute var operationType: String
    @Attribute var affectedSnapshotIDsJSON: String
    @Attribute var summary: String
    @Attribute var operationDeviceID: String
    @Attribute var operationAppBuildVersion: String

    init(operationType: String, summary: String, deviceID: String, appBuildVersion: String) {
        self.id = UUID()
        self.timestamp = Date.now
        self.operationType = operationType
        self.affectedSnapshotIDsJSON = "[]"
        self.summary = summary
        self.operationDeviceID = deviceID
        self.operationAppBuildVersion = appBuildVersion
    }
}

extension OperationLog {
    var affectedSnapshotIDs: [String] {
        get { (try? JSONDecoder().decode([String].self, from: Data(affectedSnapshotIDsJSON.utf8))) ?? [] }
        set { affectedSnapshotIDsJSON = (try? String(data: JSONEncoder().encode(newValue), encoding: .utf8)) ?? "[]" }
    }
}
