import Foundation
import SwiftData

@Model final class TypeDelta {
    @Attribute(.unique) var id: UUID
    @Attribute var typeIdentifier: String
    @Attribute var displayName: String
    @Attribute var countDelta: Int
    @Attribute var hashBefore: String
    @Attribute var hashAfter: String
    @Attribute var qualityBeforeRaw: String?
    @Attribute var qualityAfterRaw: String?
    @Attribute var transitionRaw: String
    @Attribute var reasonRaw: String
    @Attribute var yearlyCountNote: String
    @Attribute var isCloudKitImported: Bool
    var delta: SnapshotDelta?

    init(typeIdentifier: String, displayName: String) {
        self.id = UUID()
        self.typeIdentifier = typeIdentifier
        self.displayName = displayName
        self.countDelta = 0
        self.hashBefore = ""
        self.hashAfter = ""
        self.qualityBeforeRaw = nil
        self.qualityAfterRaw = nil
        self.transitionRaw = TypeTransition.unchanged.rawValue
        self.reasonRaw = TypeDeltaReason.normal.rawValue
        self.yearlyCountNote = ""
        self.isCloudKitImported = false
        self.delta = nil
    }
}

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 }
    }
}
