import Foundation

nonisolated struct SeenNotificationStore {
    private nonisolated(unsafe) let defaults: UserDefaults

    init(suiteName: String = "de.hausotte.Forji.seenNotifications") {
        defaults = UserDefaults(suiteName: suiteName) ?? .standard
    }

    private func key(for serverURL: String, username: String) -> String {
        "seen_\(serverURL)_\(username)"
    }

    private func seedKey(for serverURL: String, username: String) -> String {
        "seeded_\(serverURL)_\(username)"
    }

    func seenIDs(for serverURL: String, username: String) -> Set<Int> {
        let ids = defaults.array(forKey: key(for: serverURL, username: username)) as? [Int] ?? []
        return Set(ids)
    }

    func markSeen(_ ids: Set<Int>, for serverURL: String, username: String) {
        let existing = seenIDs(for: serverURL, username: username)
        let merged = existing.union(ids)
        defaults.set(Array(merged), forKey: key(for: serverURL, username: username))
    }

    func seed(ids: Set<Int>, for serverURL: String, username: String) {
        defaults.set(Array(ids), forKey: key(for: serverURL, username: username))
        defaults.set(true, forKey: seedKey(for: serverURL, username: username))
    }

    func isSeeded(for serverURL: String, username: String) -> Bool {
        defaults.bool(forKey: seedKey(for: serverURL, username: username))
    }

    func prune(keeping currentIDs: Set<Int>, for serverURL: String, username: String) {
        let existing = seenIDs(for: serverURL, username: username)
        let pruned = existing.intersection(currentIDs)
        defaults.set(Array(pruned), forKey: key(for: serverURL, username: username))
    }
}
