import Testing
import SwiftData
import Foundation
@testable import 康康

struct MetricReminderTests {

    private func makeContainer() throws -> ModelContainer {
        let schema = Schema([MetricReminder.self])
        let config = ModelConfiguration(schema: schema, isStoredInMemoryOnly: true)
        return try ModelContainer(for: schema, configurations: [config])
    }

    @Test func defaultsToEveryDayAt8AM() {
        let r = MetricReminder(metricId: "bloodPressure", displayName: "血压")
        #expect(r.hour == 8)
        #expect(r.minute == 0)
        #expect(r.weekdays == [1, 2, 3, 4, 5, 6, 7])
        #expect(r.enabled == true)
        #expect(r.isEveryDay)
        #expect(r.frequencyLabel == "每天")
    }

    @Test func hourMinuteClampedToValidRange() {
        let early = MetricReminder(metricId: "x", displayName: "x", hour: -5, minute: 80)
        #expect(early.hour == 0)
        #expect(early.minute == 59)
        let late = MetricReminder(metricId: "y", displayName: "y", hour: 25, minute: -3)
        #expect(late.hour == 23)
        #expect(late.minute == 0)
    }

    @Test func weekdaysRoundtripThroughSwiftData() throws {
        let container = try makeContainer()
        let ctx = ModelContext(container)
        let r = MetricReminder(
            metricId: "bloodPressure",
            displayName: "血压",
            hour: 7, minute: 30,
            weekdays: [2, 4, 6]
        )
        ctx.insert(r)
        try ctx.save()

        let fetched = try #require(try ctx.fetch(FetchDescriptor<MetricReminder>()).first)
        #expect(fetched.weekdays == [2, 4, 6])
        #expect(fetched.isEveryDay == false)
        #expect(fetched.frequencyLabel == "每周 一三五")
        #expect(fetched.timeLabel == "07:30")
    }

    @Test func disabledFrequencyLabel() {
        let r = MetricReminder(metricId: "x", displayName: "x", enabled: false)
        #expect(r.frequencyLabel == "已关闭")
    }

    @Test func emptyWeekdaysNotEveryDay() {
        let r = MetricReminder(metricId: "x", displayName: "x", weekdays: [])
        #expect(!r.isEveryDay)
        #expect(r.frequencyLabel == "未选日")
    }

    @Test func metricIdUniquenessEnforced() throws {
        let container = try makeContainer()
        let ctx = ModelContext(container)
        let r1 = MetricReminder(metricId: "bp", displayName: "血压")
        ctx.insert(r1)
        try ctx.save()

        let r2 = MetricReminder(metricId: "bp", displayName: "血压重复")
        ctx.insert(r2)
        try ctx.save()

        // SwiftData @Attribute(.unique) 在冲突时合并/拒绝(具体行为版本依赖);
        // 至少 fetch 总数 ≤ 1。
        let all = try ctx.fetch(FetchDescriptor<MetricReminder>())
        #expect(all.count == 1)
    }
}
