import Testing
import Foundation
@testable import 康康

@MainActor
struct MonitorMetricTests {

    @Test func allMetricsHaveAtLeastOneField() {
        for m in MonitorMetric.allCases {
            #expect(!m.fields.isEmpty, "metric \(m.rawValue) has no fields")
        }
    }

    @Test func bloodPressureHasTwoFields() {
        let bp = MonitorMetric.bloodPressure
        #expect(bp.fields.count == 2)
        #expect(bp.fields[0].seriesKey == "bp.systolic")
        #expect(bp.fields[1].seriesKey == "bp.diastolic")
    }

    @Test func statusHighWhenValueAboveRange() {
        let s = MonitorMetric.status(value: 150, in: 90...140)
        #expect(s == .high)
    }

    @Test func statusLowWhenValueBelowRange() {
        let s = MonitorMetric.status(value: 80, in: 90...140)
        #expect(s == .low)
    }

    @Test func statusNormalWhenValueInside() {
        let s = MonitorMetric.status(value: 120, in: 90...140)
        #expect(s == .normal)
    }

    @Test func statusNormalWhenRangeIsNil() {
        let s = MonitorMetric.status(value: 999, in: nil)
        #expect(s == .normal)
    }

    @Test func systolicUpperBoundShiftsForElderly() {
        let bp = MonitorMetric.bloodPressure
        let systolic = bp.fields[0]
        let elderly = UserProfile(birthYear: 1955)  // 71 岁
        let range = bp.effectiveRange(for: systolic, profile: elderly)
        #expect(range == 90...150)
    }

    @Test func systolicUpperBoundUnchangedForYoungAdult() {
        let bp = MonitorMetric.bloodPressure
        let systolic = bp.fields[0]
        let young = UserProfile(birthYear: 1990)
        let range = bp.effectiveRange(for: systolic, profile: young)
        #expect(range == 90...140)
    }

    @Test func systolicUpperBoundUnchangedWhenProfileNil() {
        let bp = MonitorMetric.bloodPressure
        let systolic = bp.fields[0]
        let range = bp.effectiveRange(for: systolic, profile: nil)
        #expect(range == 90...140)
    }

    @Test func glucoseUnaffectedByAge() {
        let g = MonitorMetric.fastingGlucose
        let field = g.fields[0]
        let elderly = UserProfile(birthYear: 1940)
        #expect(g.effectiveRange(for: field, profile: elderly) == field.baseRange)
    }

    @Test func isRangePersonalizedTrueForElderlySystolic() {
        let bp = MonitorMetric.bloodPressure
        let systolic = bp.fields[0]
        let elderly = UserProfile(birthYear: 1955)
        #expect(bp.isRangePersonalized(for: systolic, profile: elderly) == true)
    }

    @Test func isRangePersonalizedFalseForYoungProfile() {
        let bp = MonitorMetric.bloodPressure
        let systolic = bp.fields[0]
        let young = UserProfile(birthYear: 1995)
        #expect(bp.isRangePersonalized(for: systolic, profile: young) == false)
    }
}
