import request from 'supertest'
import { generateSimpleViteManifest, mockApp, mockConfig, mockFetch, mockRedis } from './util.js'
import { expect } from 'chai'
import { Response } from 'node-fetch'
import * as td from 'testdouble'
import RedisMock from 'ioredis-mock'

describe('JS files with dependencies contain events', function () {
  let app

  before(async function () {
    mockConfig({ urls: ['http://ui-server/'] })
    mockRedis()
    mockFetch({
      'http://ui-server': {
        '/manifest.json': generateSimpleViteManifest({
          'example.js': {},
          'main.css': {},
          'index.html': {
            file: 'index.html.js',
            isEntry: true,
            imports: ['example.js'],
            css: ['main.css']
          }
        }),
        '/example.js': () => new Response('this is example', { headers: { 'content-type': 'application/javascript' } }),
        '/index.html.js': () => new Response('console.log("this is index.html.js")', { headers: { 'content-type': 'application/javascript' } }),
        '/index.html': () => new Response('<html><head></head><body>it\'s me</body></html>', { headers: { 'content-type': 'text/html' } }),
        '/main.css': () => new Response('.foo { color: #000; }', { headers: { 'content-type': 'text/css' } })
      }
    })
    app = await mockApp()
  })

  afterEach(async function () {
    await new RedisMock().flushdb()
  })

  after(function () {
    td.reset()
  })

  it('javascript file contains dispatcher for dependencies', async function () {
    const response = await request(app).get('/index.html.js')
    expect(response.statusCode).to.equal(200)
    expect(response.headers.dependencies).to.equal('main.css')
    expect(response.text).to.equal('console.log("this is index.html.js")\n/*injected by ui-middleware*/document.dispatchEvent(new CustomEvent("load-css",{detail:{css:["main.css"]}}))')
  })
})