import Foundation

struct PrototypeStoreResetResult: Equatable {
    let didReset: Bool
    let removedURLs: [URL]
}

enum PrototypeStoreResetPolicy {
    static let currentGeneration = 1
    static let defaultsKey = "hp_prototypeStoreResetGeneration"

    static func applyIfNeeded(
        appSupportURL: URL = .applicationSupportDirectory,
        defaults: UserDefaults = .standard,
        fileManager: FileManager = .default
    ) throws -> PrototypeStoreResetResult {
        guard defaults.integer(forKey: defaultsKey) < currentGeneration else {
            return PrototypeStoreResetResult(didReset: false, removedURLs: [])
        }

        var removedURLs: [URL] = []
        for url in destructiveResetURLs(appSupportURL: appSupportURL) {
            guard fileManager.fileExists(atPath: url.path) else { continue }
            try fileManager.removeItem(at: url)
            removedURLs.append(url)
        }

        defaults.set(currentGeneration, forKey: defaultsKey)
        return PrototypeStoreResetResult(didReset: true, removedURLs: removedURLs)
    }

    static func destructiveResetURLs(appSupportURL: URL) -> [URL] {
        sidecarURLs(
            forBaseNames: [
                "HealthProbeRecords.store",
                "HealthProbeCloud.store",
                "HealthProbeArchive.sqlite",
                "HealthProbeCache.sqlite"
            ],
            appSupportURL: appSupportURL
        )
    }

    private static func sidecarURLs(forBaseNames baseNames: [String], appSupportURL: URL) -> [URL] {
        baseNames.flatMap { baseName in
            let baseURL = appSupportURL.appending(path: baseName)
            return [
                baseURL,
                appSupportURL.appending(path: "\(baseName)-shm"),
                appSupportURL.appending(path: "\(baseName)-wal"),
                appSupportURL.appending(path: "\(baseName).shm"),
                appSupportURL.appending(path: "\(baseName).wal")
            ]
        }
    }
}
