import Foundation
import SwiftData
import Testing
@testable import Andromida

struct RitualStoreTests {
    @MainActor
    @Test func quickRitualStartsIncomplete() throws {
        let store = makeStore()
        store.createQuickRitual()

        #expect(store.activeRitual != nil)
        #expect(abs(store.activeRitualProgress) < 0.0001)
    }

    @MainActor
    @Test func toggleHabitCompletionMarksComplete() throws {
        let store = makeStore()
        store.createQuickRitual()

        guard let habit = store.activeRitual?.habits.first else {
            throw TestError.missingHabit
        }

        store.toggleHabitCompletion(habit)
        #expect(store.isHabitCompletedToday(habit) == true)
    }
    
    @MainActor
    @Test func arcRenewalCreatesNewArc() throws {
        let store = makeStore()
        store.createQuickRitual()
        
        guard let ritual = store.activeRitual else {
            throw TestError.missingHabit
        }
        
        #expect(ritual.arcs.count == 1)
        #expect(ritual.currentArc?.arcNumber == 1)
        
        // End the current arc
        store.endArc(for: ritual)
        
        #expect(ritual.currentArc == nil)
        
        // Renew the arc
        store.renewArc(for: ritual, durationDays: 30, copyHabits: true)
        
        #expect(ritual.arcs.count == 2)
        #expect(ritual.currentArc?.arcNumber == 2)
        #expect(ritual.currentArc?.habits.count == 3)
    }
}

@MainActor
private func makeStore() -> RitualStore {
    let schema = Schema([Ritual.self, RitualArc.self, ArcHabit.self])
    let configuration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: true)
    let container: ModelContainer
    do {
        container = try ModelContainer(for: schema, configurations: [configuration])
    } catch {
        fatalError("Test container failed: \(error)")
    }

    return RitualStore(modelContext: container.mainContext, seedService: EmptySeedService(), settingsStore: SettingsStore())
}

private struct EmptySeedService: RitualSeedProviding {
    func makeSeedRituals(startDate: Date) -> [Ritual] {
        []
    }
}

private enum TestError: Error {
    case missingHabit
}
