import { expect } from 'chai'
import { generateSimpleViteManifest, injectApp, mockConfig, mockFetch, wait } from '../spec/util.js'
import * as td from 'testdouble'
import { getRedisKey } from '../src/util.js'

describe('Configuration', function () {
  let app
  let config

  beforeEach(async function () {
    // need to set the redis-prefix. Otherwise, the bull workers will interfere
    process.env.REDIS_PREFIX = Math.random().toString()
    mockConfig(config = { baseUrls: ['http://ui-server/'] })
    mockFetch({
      'http://ui-server': {
        '/manifest.json': generateSimpleViteManifest({
          'index.html': {}
        }),
        '/index.html': () => new Response('<html><head></head><body>it\'s me</body></html>', { headers: { 'content-type': 'text/html' } }),
        '/meta.json': td.when(td.func()(td.matchers.anything(), td.matchers.anything())).thenReturn(
          new Response(JSON.stringify({ commitSha: '1' }), { headers: { 'Content-Type': 'application/json' } }),
          new Response(JSON.stringify({ commitSha: '2' }), { headers: { 'Content-Type': 'application/json' } })
        )
      }
    })
    await import('../src/redis.js').then(({ client }) => client.flushdb())
    app = await injectApp()
  })

  afterEach(async function () {
    const { getQueues, closeQueue } = await import('../src/redis.js')
    for (const queue of getQueues()) {
      await closeQueue(queue.name)
    }
    td.reset()
    // reset, after the queues were removed
    process.env.REDIS_PREFIX = 'ui-middleware'
  })

  it('updates the configuration when updated on a different node', async function () {
    const response = await app.inject({ url: '/meta' })
    expect(response.json()).to.have.length(2)

    config.baseUrls = []
    const { pubClient } = await import('../src/redis.js')
    pubClient.publish(getRedisKey({ name: 'updateVersionInfo' }), JSON.stringify({ version: '1234' }))
    await wait(200)

    const response2 = await app.inject({ url: '/meta' })
    expect(response2.json()).to.have.length(1)
  })
})