import Foundation
import Testing
import UserNotifications

@testable import Forji

struct SeenNotificationStoreTests {
    private func makeStore() -> SeenNotificationStore {
        let suite = "de.hausotte.Forji.test.\(UUID().uuidString)"
        return SeenNotificationStore(suiteName: suite)
    }

    @Test func seedSetsIDsAndMarksAsSeeded() {
        let store = makeStore()
        let server = "https://example.com"
        let user = "alice"

        #expect(!store.isSeeded(for: server, username: user))

        store.seed(ids: [1, 2, 3], for: server, username: user)

        #expect(store.isSeeded(for: server, username: user))
        #expect(store.seenIDs(for: server, username: user) == [1, 2, 3])
    }

    @Test func markSeenIsAdditive() {
        let store = makeStore()
        let server = "https://example.com"
        let user = "alice"

        store.seed(ids: [1, 2], for: server, username: user)
        store.markSeen([3, 4], for: server, username: user)

        #expect(store.seenIDs(for: server, username: user) == [1, 2, 3, 4])
    }

    @Test func pruneRemovesStaleIDs() {
        let store = makeStore()
        let server = "https://example.com"
        let user = "alice"

        store.seed(ids: [1, 2, 3, 4, 5], for: server, username: user)
        store.prune(keeping: [2, 4], for: server, username: user)

        #expect(store.seenIDs(for: server, username: user) == [2, 4])
    }

    @Test func perInstanceIsolation() {
        let store = makeStore()

        store.seed(ids: [1, 2], for: "https://a.com", username: "alice")
        store.seed(ids: [10, 20], for: "https://b.com", username: "bob")

        #expect(store.seenIDs(for: "https://a.com", username: "alice") == [1, 2])
        #expect(store.seenIDs(for: "https://b.com", username: "bob") == [10, 20])
    }

    @Test func emptyStoreReturnsEmptySet() {
        let store = makeStore()
        #expect(store.seenIDs(for: "https://x.com", username: "nobody").isEmpty)
    }

    @Test func isSeededReturnsFalseForUnknownInstance() {
        let store = makeStore()
        #expect(!store.isSeeded(for: "https://x.com", username: "nobody"))
    }

    @Test func markSeenOnUnseededStoreWorks() {
        let store = makeStore()
        let server = "https://example.com"
        let user = "alice"

        store.markSeen([5, 6], for: server, username: user)
        #expect(store.seenIDs(for: server, username: user) == [5, 6])
    }

    @Test @MainActor func disableNotificationsClearsFlag() async {
        let key = "notificationsEnabled"
        UserDefaults.standard.set(true, forKey: key)
        #expect(UserDefaults.standard.bool(forKey: key) == true)

        await NotificationPollingService.shared.stopForegroundPolling()
        UserDefaults.standard.set(false, forKey: key)
        try? await UNUserNotificationCenter.current().setBadgeCount(0)

        #expect(UserDefaults.standard.bool(forKey: key) == false)
    }
}
