import test from "node:test"
import assert from "node:assert/strict"

import {
  HIDDEN_MESSAGE_IDS_STORAGE_KEY,
  getHiddenMessageIds,
  persistHiddenMessageId
} from "../src/lib/hiddenMessages.ts"

function createMemoryStorage(initialValue?: string) {
  const values = new Map<string, string>()
  if (initialValue !== undefined) {
    values.set(HIDDEN_MESSAGE_IDS_STORAGE_KEY, initialValue)
  }

  return {
    getItem(key: string) {
      return values.get(key) ?? null
    },
    setItem(key: string, value: string) {
      values.set(key, value)
    }
  }
}

test("persists hidden message ids by session", () => {
  const storage = createMemoryStorage()

  persistHiddenMessageId("session-a", "message-1", storage)
  persistHiddenMessageId("session-a", "message-2", storage)
  persistHiddenMessageId("session-b", "message-3", storage)

  assert.deepEqual([...getHiddenMessageIds("session-a", storage)], ["message-1", "message-2"])
  assert.deepEqual([...getHiddenMessageIds("session-b", storage)], ["message-3"])
})

test("deduplicates hidden message ids and ignores invalid storage", () => {
  const invalidStorage = createMemoryStorage("{")
  assert.deepEqual([...getHiddenMessageIds("session-a", invalidStorage)], [])

  const storage = createMemoryStorage()
  persistHiddenMessageId("session-a", "message-1", storage)
  persistHiddenMessageId("session-a", "message-1", storage)

  assert.deepEqual([...getHiddenMessageIds("session-a", storage)], ["message-1"])
})
