import request from 'supertest'
import { expect } from 'chai'
import { generateSimpleViteManifest, mockApp, mockConfig, mockFetch } from '../spec/util.js'
import { client, closeQueue, getQueues, pubClient } from '../src/redis.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()
    await client.flushdb()
    mockConfig(config = { urls: ['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())).thenReturn(
          new Response(JSON.stringify({ commitSha: '1' }), { headers: { 'Content-Type': 'application/json' } }),
          new Response(JSON.stringify({ commitSha: '2' }), { headers: { 'Content-Type': 'application/json' } })
        )
      }
    })
    app = await mockApp()
  })

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

  it('updates the configuration when updated on a different node', async function () {
    // need to do this with dynamic import such that the mocked config is used
    await import('../src/create-queues.js').then(({ default: createQueues }) => createQueues())

    const response = await request(app.server).get('/meta')
    expect(response.body).to.have.length(2)

    config.urls = []
    pubClient.publish(getRedisKey({ name: 'updateLatestVersion' }), '1234')
    await new Promise(resolve => setTimeout(resolve, 200))

    const response2 = await request(app.server).get('/meta')
    expect(response2.body).to.have.length(1)
  })
})