import AppKit
import Foundation

@MainActor
final class FolderAccessService {
    private let bookmarkKey = "velody.selected-folder.bookmark"

    func chooseFolder() -> URL? {
        let panel = NSOpenPanel()
        panel.canChooseDirectories = true
        panel.canChooseFiles = false
        panel.allowsMultipleSelection = false
        panel.prompt = "Choose Folder"

        guard panel.runModal() == .OK, let url = panel.url else {
            return nil
        }

        do {
            let bookmark = try url.bookmarkData(
                options: [.withSecurityScope],
                includingResourceValuesForKeys: nil,
                relativeTo: nil
            )
            UserDefaults.standard.set(bookmark, forKey: bookmarkKey)
            return url
        } catch {
            return url
        }
    }

    func storedFolderURL() -> URL? {
        guard
            let bookmark = UserDefaults.standard.data(forKey: bookmarkKey)
        else {
            return nil
        }

        var isStale = false
        return try? URL(
            resolvingBookmarkData: bookmark,
            options: [.withSecurityScope],
            relativeTo: nil,
            bookmarkDataIsStale: &isStale
        )
    }
}
