import { test } from '@japa/runner'
import { find, store, clear } from '../../../../src/runtime/variables/Cache.js'

const target1 = Object()
const target2 = Object()

test.group('store()', (group) => {
  const key = 'abc'
  const groupName = '1'

  group.each.teardown(() => {
    clear(target1)
    clear(target2)
  })

  test('stores data in cache', ({ assert }) => {
    store(target1, key, groupName, 'test')
    const value = find(target1, key, groupName)
    assert.equal(value, 'test')
  })

  test('stores multiple values', ({ assert }) => {
    store(target1, key, '2', 'other')
    const value = find(target1, key, '2')
    assert.equal(value, 'other')
  })

  test('uses different keys', ({ assert }) => {
    store(target1, 'my-key', '2', 'other')
    const value = find(target1, 'my-key', '2')
    assert.equal(value, 'other')
  })

  test('handles multiple objects', ({ assert }) => {
    store(target1, key, groupName, 'test-1')
    store(target2, key, groupName, 'test-2')
    const value1 = find(target1, key, groupName)
    assert.equal(value1, 'test-1', 'stores for first target')
    const value2 = find(target2, key, groupName)
    assert.equal(value2, 'test-2', 'stores for other target')
  })
})

test.group('find()', (group) => {
  const key = 'abc'
  const groupName = '1'

  group.each.teardown(() => {
    clear(target1)
    clear(target2)
  })

  test('returns null when no stored data', ({ assert }) => {
    const value = find(target1, key, groupName)
    assert.equal(value, null)
  })

  test('returns null when no value for the key', ({ assert }) => {
    store(target1, 'my-key', '2', 'other')
    const value = find(target1, key, groupName)
    assert.equal(value, null)
  })

  test('returns null when no value for the group', ({ assert }) => {
    store(target1, key, '2', 'other')
    const value = find(target1, key, groupName)
    assert.equal(value, null)
  })

  test('returns the value', ({ assert }) => {
    store(target1, key, groupName, 'test')
    const value = find(target1, key, groupName)
    assert.equal(value, 'test')
  })
})

test.group('clear()', () => {
  const key = 'abc'
  const group = '1'

  test('clears data for a target', ({ assert }) => {
    store(target1, key, group, 'test')
    clear(target1)
    const value = find(target1, key, group)
    assert.equal(value, null)
  })

  test('clears data for the passed target only', ({ assert }) => {
    store(target1, key, group, 'test')
    store(target2, key, group, 'test')
    clear(target1)
    const value = find(target2, key, group)
    assert.equal(value, 'test')
  })
})
