import Foundation

/// Creation and resolution of security-scoped bookmarks. On iOS these are
/// inode-based, so they survive the file being moved or renamed on the same volume.
enum BookmarkService {
    struct Resolved {
        var url: URL
        var wasStale: Bool
        /// Present when the system flagged the bookmark stale and a fresh one was minted.
        var refreshedBookmark: Data?
    }

    static func createBookmark(for url: URL) throws -> Data {
        try url.bookmarkData(options: [], includingResourceValuesForKeys: nil, relativeTo: nil)
    }

    static func resolve(_ data: Data) -> Resolved? {
        var isStale = false
        guard let url = try? URL(resolvingBookmarkData: data, options: [], relativeTo: nil, bookmarkDataIsStale: &isStale) else {
            return nil
        }
        var refreshed: Data?
        if isStale {
            let accessing = url.startAccessingSecurityScopedResource()
            refreshed = try? createBookmark(for: url)
            if accessing { url.stopAccessingSecurityScopedResource() }
        }
        return Resolved(url: url, wasStale: isStale, refreshedBookmark: refreshed)
    }
}
