import Foundation
import SwiftData

@Model final class TypeDelta {
    var id: UUID = UUID()
    var typeIdentifier: String = ""
    var displayName: String = ""
    var countDelta: Int = 0
    var hashBefore: String = ""
    var hashAfter: String = ""
    var qualityBeforeRaw: String? = nil   // SnapshotQuality.rawValue; nil if type didn't exist
    var qualityAfterRaw: String? = nil    // SnapshotQuality.rawValue; nil if type doesn't exist
    var transitionRaw: String = TypeTransition.unchanged.rawValue
    var reasonRaw: String = TypeDeltaReason.normal.rawValue
    var yearlyCountNote: String = ""
    var isCloudKitImported: Bool = false
    // nil is valid ONLY as a transient CloudKit sync state (isCloudKitImported == true).
    // Locally created TypeDeltas must always have a parent at save time — nil on a locally
    // committed delta is a bug. Chain validation tolerates nil only for CloudKit-pending records.
    var delta: SnapshotDelta?

    init(typeIdentifier: String, displayName: String) {
        self.id = UUID()
        self.typeIdentifier = typeIdentifier
        self.displayName = displayName
    }
}

extension TypeDelta {
    var transition: TypeTransition {
        get { TypeTransition(rawValue: transitionRaw) ?? .unchanged }
        set { transitionRaw = newValue.rawValue }
    }
    var reason: TypeDeltaReason {
        get { TypeDeltaReason(rawValue: reasonRaw) ?? .unknown }
        set { reasonRaw = newValue.rawValue }
    }
    var qualityBefore: SnapshotQuality? {
        get { qualityBeforeRaw.flatMap { SnapshotQuality(rawValue: $0) } }
        set { qualityBeforeRaw = newValue?.rawValue }
    }
    var qualityAfter: SnapshotQuality? {
        get { qualityAfterRaw.flatMap { SnapshotQuality(rawValue: $0) } }
        set { qualityAfterRaw = newValue?.rawValue }
    }
}
