import Foundation
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([Split.self, Exercise.self, Workout.self, WorkoutLog.self])
        let config = ModelConfiguration(schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)
        return SyncEngine(container: try ModelContainer(for: schema, configurations: [config]))
    }

    /// With no clone-on-edit fork recorded, `currentSplitID` is the identity — a view
    /// holding a split 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 currentSplitIDIsIdentityWithoutRedirects() throws {
        let engine = try makeEngine()
        #expect(engine.currentSplitID(for: "01SEEDABCDEFGHJKMNPQRSTVWX") == "01SEEDABCDEFGHJKMNPQRSTVWX")
        #expect(engine.currentSplitID(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)
    }
}
