import Foundation
import IndieSync
import SwiftData
import Testing
@testable import Workouts

/// Coverage for the parts of `SyncEngine` reachable without a live iCloud container.
///
/// SCOPE NOTE: `SyncEngine`'s orchestration (`save`/`delete`/`reconcile`/`reconcileSeeds`)
/// resolves its `DocumentFileStore` *inside* `connect()` from the real ubiquity
/// container — there is no seam to inject a fake store, and the task deliberately rules
/// out building a heavyweight `NSMetadataQuery` mock. So the file-touching paths (incl.
/// FIX-1's rebucketing removal and FIX-2's `.upgrade` stub re-check) are not unit-testable
/// here without refactoring `SyncEngine` to accept an injected store — out of scope.
/// Their *pure* decision logic is already locked elsewhere: `SeedReconcilePlannerTests`
/// (the seed skip/upgrade/write table, incl. the veto that FIX-2 re-checks),
/// `DuplicateCleanupPlannerTests`, `WorkoutPathBucketingTests` (FIX-1's path divergence),
/// and `WorkoutStatusMachineTests`. What remains directly testable is the pure
/// in-memory redirect helper below.
struct SyncEngineTests {

    @MainActor
    private func makeEngine() throws -> SyncEngine {
        let schema = Schema([Routine.self, Exercise.self, Workout.self, WorkoutLog.self])
        let config = ModelConfiguration(schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)
        let backlogURL = FileManager.default.temporaryDirectory
            .appending(path: "SyncEngineTests-\(UUID().uuidString).json")
        return SyncEngine(container: try ModelContainer(for: schema, configurations: [config]),
                          backlogURL: backlogURL)
    }

    /// A minimal workout document with one log, both carrying the given statuses.
    private func makeWorkout(id: String, status: WorkoutStatus, logStatus: WorkoutStatus) -> WorkoutDocument {
        let now = Date()
        var log = WorkoutLogDocument(planFrom: ExerciseDocument(
            id: ULID.make(), name: "Seated Row", order: 0, sets: 3, reps: 10,
            weight: 90, loadType: LoadType.weight.rawValue, durationSeconds: 0), order: 0, date: now)
        log.status = logStatus.rawValue
        return WorkoutDocument(
            schemaVersion: WorkoutDocument.currentSchemaVersion, id: id,
            routineID: nil, routineName: "Upper Body", start: now, end: nil,
            status: status.rawValue, createdAt: now, updatedAt: now, logs: [log])
    }

    /// Locks `onWorkoutBecameActive`'s trigger table: it fires exactly once, on a
    /// phone-side `.notStarted` → `.inProgress` transition — not on draft creation,
    /// not on a repeat in-progress save, not for a watch-originated update, and not
    /// when an old workout is edited from `.completed` back to `.inProgress`.
    @MainActor
    @Test func becameActiveFiresOnlyOnLocalNotStartedToInProgress() async throws {
        let engine = try makeEngine()
        var fired: [String] = []
        engine.onWorkoutBecameActive = { fired.append($0.id) }

        // Draft creation: notStarted → no fire.
        let id = ULID.make()
        await engine.save(workout: makeWorkout(id: id, status: .notStarted, logStatus: .notStarted))
        #expect(fired.isEmpty)

        // First exercise starts: notStarted → inProgress fires once.
        await engine.save(workout: makeWorkout(id: id, status: .inProgress, logStatus: .inProgress))
        #expect(fired == [id])

        // Re-saving an already-active run doesn't re-fire.
        await engine.save(workout: makeWorkout(id: id, status: .inProgress, logStatus: .inProgress))
        #expect(fired == [id])

        // A watch-originated start never fires — the watch already owns a session.
        let watchID = ULID.make()
        await engine.ingestFromWatch(makeWorkout(id: watchID, status: .inProgress, logStatus: .inProgress))
        #expect(fired == [id])

        // Editing a finished workout back to in-progress isn't a fresh start.
        let oldID = ULID.make()
        await engine.save(workout: makeWorkout(id: oldID, status: .completed, logStatus: .completed))
        await engine.save(workout: makeWorkout(id: oldID, status: .inProgress, logStatus: .inProgress))
        #expect(fired == [id])
    }

    /// With no clone-on-edit fork recorded, `currentRoutineID` is the identity — a view
    /// holding a routine id resolves to that same id. This pins the redirect-follow loop's
    /// base case and its termination (no redirect → return input, no infinite loop).
    @MainActor
    @Test func currentRoutineIDIsIdentityWithoutRedirects() throws {
        let engine = try makeEngine()
        #expect(engine.currentRoutineID(for: "01SEEDABCDEFGHJKMNPQRSTVWX") == "01SEEDABCDEFGHJKMNPQRSTVWX")
        #expect(engine.currentRoutineID(for: "") == "")
    }

    /// A freshly constructed engine is in the `.checking` state until `connect()` runs,
    /// and exposes no sync error.
    @MainActor
    @Test func freshEngineIsCheckingWithNoError() throws {
        let engine = try makeEngine()
        #expect(engine.iCloudStatus == .checking)
        #expect(engine.lastSyncError == nil)
        #expect(!engine.isSyncing)
    }
}
