import Foundation
import SwiftData

@Model final class SnapshotDelta {
    var id: UUID = UUID()
    var fromSnapshotID: UUID = UUID()
    var toSnapshotID: UUID = UUID()
    var deviceID: String = ""
    var computedAt: Date = Date.now
    var checksumBefore: String = ""
    var checksumAfter: String = ""
    var listSummaryVersion: Int = 0
    var absoluteRecordChangeCount: Int = 0
    var changedMetricCount: Int = 0
    var appearedMetricCount: Int = 0
    var disappearedMetricCount: Int = 0
    @Relationship(deleteRule: .cascade, inverse: \TypeDelta.delta)
    var typeDeltas: [TypeDelta]? = []

    init(fromSnapshotID: UUID, toSnapshotID: UUID, deviceID: String) {
        self.id = UUID()
        self.fromSnapshotID = fromSnapshotID
        self.toSnapshotID = toSnapshotID
        self.deviceID = deviceID
    }
}

struct SnapshotDeltaListSummary {
    let absoluteRecordChangeCount: Int
    let changedMetricCount: Int
    let appearedMetricCount: Int
    let disappearedMetricCount: Int

    var affectedMetricCount: Int {
        changedMetricCount + appearedMetricCount + disappearedMetricCount
    }

    var hasChanges: Bool {
        absoluteRecordChangeCount > 0 || affectedMetricCount > 0
    }
}

extension SnapshotDelta {
    static let currentListSummaryVersion = 1

    var listSummary: SnapshotDeltaListSummary {
        SnapshotDeltaListSummary(
            absoluteRecordChangeCount: absoluteRecordChangeCount,
            changedMetricCount: changedMetricCount,
            appearedMetricCount: appearedMetricCount,
            disappearedMetricCount: disappearedMetricCount
        )
    }
}
