import XCTest
@testable import HealthProbe

final class PrototypeStoreResetPolicyTests: XCTestCase {
    private var temporaryDirectory: URL!
    private var defaults: UserDefaults!
    private var defaultsSuiteName: String!

    override func setUpWithError() throws {
        temporaryDirectory = FileManager.default.temporaryDirectory
            .appending(path: "HealthProbeResetTests-\(UUID().uuidString)", directoryHint: .isDirectory)
        try FileManager.default.createDirectory(at: temporaryDirectory, withIntermediateDirectories: true)
        defaultsSuiteName = "HealthProbeResetTests-\(UUID().uuidString)"
        defaults = UserDefaults(suiteName: defaultsSuiteName)
        defaults.removePersistentDomain(forName: defaultsSuiteName)
    }

    override func tearDownWithError() throws {
        if let temporaryDirectory {
            try? FileManager.default.removeItem(at: temporaryDirectory)
        }
        if let defaults {
            defaults.removePersistentDomain(forName: defaultsSuiteName)
        }
        temporaryDirectory = nil
        defaults = nil
        defaultsSuiteName = nil
    }

    func testApplyIfNeededRemovesPrototypeArchiveAndCacheStoresOnce() throws {
        let files = [
            "HealthProbeRecords.store",
            "HealthProbeRecords.store-wal",
            "HealthProbeArchive.sqlite",
            "HealthProbeArchive.sqlite-shm",
            "HealthProbeCache.sqlite"
        ]
        for file in files {
            try Data("prototype".utf8).write(to: temporaryDirectory.appending(path: file))
        }
        try Data("settings".utf8).write(to: temporaryDirectory.appending(path: "HealthProbeLocal.store"))

        let first = try PrototypeStoreResetPolicy.applyIfNeeded(
            appSupportURL: temporaryDirectory,
            defaults: defaults
        )
        XCTAssertTrue(first.didReset)
        XCTAssertEqual(Set(first.removedURLs.map(\.lastPathComponent)), Set(files))
        for file in files {
            XCTAssertFalse(FileManager.default.fileExists(atPath: temporaryDirectory.appending(path: file).path))
        }
        XCTAssertTrue(FileManager.default.fileExists(atPath: temporaryDirectory.appending(path: "HealthProbeLocal.store").path))

        let second = try PrototypeStoreResetPolicy.applyIfNeeded(
            appSupportURL: temporaryDirectory,
            defaults: defaults
        )
        XCTAssertFalse(second.didReset)
        XCTAssertTrue(second.removedURLs.isEmpty)
    }
}
