import Foundation
import SwiftData

// Interface updated 2026-05-12 — see AGENTS.md
@Model final class TypeCount {
    var id: UUID = UUID()
    var typeIdentifier: String = ""
    var displayName: String = ""
    var count: Int = 0
    var contentHash: String = ""
    var earliestDate: Date?
    var latestDate: Date?
    var qualityRaw: String = SnapshotQuality.complete.rawValue
    var isUnsupported: Bool = false
    var recordArchiveData: Data?
    var snapshot: HealthSnapshot?
    @Relationship(deleteRule: .cascade, inverse: \YearlyCount.typeCount)
    var yearlyCounts: [YearlyCount]? = []
    @Relationship(deleteRule: .cascade, inverse: \HealthRecord.typeCount)
    var records: [HealthRecord]? = []
    @Relationship(deleteRule: .cascade, inverse: \TypeDistributionBin.typeCount)
    var distributionBins: [TypeDistributionBin]? = []

    init(typeIdentifier: String, displayName: String, count: Int, quality: SnapshotQuality = .complete) {
        self.id = UUID()
        self.typeIdentifier = typeIdentifier
        self.displayName = displayName
        self.count = count
        self.qualityRaw = quality.rawValue
    }
}

extension TypeCount {
    var quality: SnapshotQuality {
        get { SnapshotQuality(rawValue: qualityRaw) ?? .complete }
        set { qualityRaw = newValue.rawValue }
    }

    var recordValues: [HealthRecordValue] {
        if let recordArchiveData,
           let decoded = HealthRecordArchive.decode(recordArchiveData) {
            return decoded
        }

        return []
    }

    func setRecordValues(_ values: [HealthRecordValue]) {
        recordArchiveData = HealthRecordArchive.encode(values)
        records?.removeAll()
    }
}
