import Foundation
import Testing
import IndieSync
@testable import Workouts

/// Pins `WorkoutDocument.relativePath` — the `Workouts/YYYY/MM/<ULID>.json` month
/// bucketing that decides where every workout file lives. The bucket derives from
/// `start` through a gregorian `Calendar`, which uses `TimeZone.current`, so the
/// tests build their dates from explicit components in that same calendar and stay
/// mid-month/mid-day (day 15, noon) so no real-world UTC offset (±14 h) can shift the
/// month — making every assertion time-zone-independent. Also documents the orphan
/// condition FIX-1 addresses in `SyncEngine.save(workout:)`: editing `start` across a
/// month boundary re-buckets the SAME id to a new path.
struct WorkoutPathBucketingTests {

    /// A date fixed to the 15th at noon in the gregorian calendar's current time zone —
    /// far enough from any month edge that the UTC-offset ambiguity can't move the month
    /// (matches `DuplicateCleanupPlannerTests.fixedDate`). Decomposed by `relativePath`'s
    /// own `Calendar(identifier: .gregorian)`, the year/month come back stable.
    private func date(year: Int, month: Int, day: Int = 15, hour: Int = 12) -> Date {
        var comps = DateComponents()
        comps.year = year
        comps.month = month
        comps.day = day
        comps.hour = hour
        return Calendar(identifier: .gregorian).date(from: comps)!
    }

    @Test func bucketsByYearAndMonth() {
        let path = WorkoutDocument.relativePath(id: "01ABC", start: date(year: 2024, month: 3))
        #expect(path == "Workouts/2024/03/01ABC.json")
    }

    /// The month is zero-padded to two digits so lexical sort matches chronological sort.
    @Test func padsSingleDigitMonth() {
        #expect(WorkoutDocument.relativePath(id: "X", start: date(year: 2025, month: 1))
                == "Workouts/2025/01/X.json")
        #expect(WorkoutDocument.relativePath(id: "X", start: date(year: 2025, month: 9))
                == "Workouts/2025/09/X.json")
    }

    /// December → January crosses the year, not just the month bucket.
    @Test func crossesYearBoundary() {
        #expect(WorkoutDocument.relativePath(id: "DEC", start: date(year: 2024, month: 12))
                == "Workouts/2024/12/DEC.json")
        #expect(WorkoutDocument.relativePath(id: "JAN", start: date(year: 2025, month: 1))
                == "Workouts/2025/01/JAN.json")
    }

    /// The instance `relativePath` property and the static computation agree — the
    /// document's own bucket is exactly what the engine writes it to.
    @Test func instancePropertyMatchesStatic() {
        let doc = WorkoutDocument(
            schemaVersion: WorkoutDocument.currentSchemaVersion, id: "01WK", routineID: nil,
            routineName: nil, start: date(year: 2024, month: 7), end: nil,
            status: WorkoutStatus.notStarted.rawValue, createdAt: date(year: 2024, month: 7),
            updatedAt: date(year: 2024, month: 7), logs: [], metrics: nil
        )
        #expect(doc.relativePath == "Workouts/2024/07/01WK.json")
        #expect(doc.relativePath == WorkoutDocument.relativePath(id: doc.id, start: doc.start))
    }

    /// FIX-1 (rebucketing orphan) — path-computation level. `SyncEngine.save(workout:)`
    /// needs a live iCloud container to exercise directly, so this pins the invariant it
    /// relies on: the SAME workout id, saved after its `start` moves to a different month,
    /// resolves to a DIFFERENT path. The old file at the previous bucket is therefore an
    /// orphan the engine must now remove (same id lives on at the new path → plain
    /// removal, no tombstone). If these two paths were ever equal the fix would be a
    /// no-op; this test guarantees they diverge exactly when the month changes.
    @Test func editingStartMonthRebucketsSameID() {
        let id = "01WORKOUTREBUCKET00000001"
        let marchStart = date(year: 2024, month: 3)
        let aprilStart = date(year: 2024, month: 4)

        let oldPath = WorkoutDocument.relativePath(id: id, start: marchStart)
        let newPath = WorkoutDocument.relativePath(id: id, start: aprilStart)

        #expect(oldPath != newPath)                              // the orphan-producing divergence
        #expect(oldPath == "Workouts/2024/03/\(id).json")
        #expect(newPath == "Workouts/2024/04/\(id).json")
        // Same-month edits (e.g. bumping the day/hour) keep the path stable → no orphan,
        // no removal.
        let sameMonthLater = date(year: 2024, month: 3, day: 28, hour: 6)
        #expect(WorkoutDocument.relativePath(id: id, start: sameMonthLater) == oldPath)
    }
}
