import Foundation

@Observable
final class DataTypesViewModel {
    var filter: DiffFilter = .all
    var comparisonMode: ComparisonMode = .previous

    private let diffService = SnapshotDiffService.shared

    func diffs(current: HealthSnapshot?, snapshots: [HealthSnapshot]) -> [TypeDiff] {
        guard let current else { return [] }
        guard let baseline = resolveBaseline(for: current, in: snapshots) else { return [] }
        let all = diffService.diff(current: current, baseline: baseline)
        return diffService.apply(filter: filter, to: all)
    }

    private func resolveBaseline(for snapshot: HealthSnapshot, in snapshots: [HealthSnapshot]) -> HealthSnapshot? {
        let sorted = snapshots.sorted { $0.timestamp > $1.timestamp }
        switch comparisonMode {
        case .previous:
            return sorted.first { $0.timestamp < snapshot.timestamp }
        case .selected:
            return nil  // DataTypesView uses .previous by default; selection lives in SnapshotsTab
        case .relativeTime(let interval):
            let target = snapshot.timestamp.addingTimeInterval(-interval)
            return diffService.nearest(to: target, in: snapshots)
        }
    }
}
