/**
 * @copyright Copyright (c) Open-Xchange GmbH, Germany <info@open-xchange.com>
 * @license AGPL-3.0
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with OX App Suite. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
 *
 * Any use of the work other than as authorized under this license or copyright law is prohibited.
 */

import { generateSimpleViteManifest, injectApp, mockConfig, mockFetch, mockRedis } from './util.js'
import { expect } from 'chai'
import * as td from 'testdouble'
import RedisMock from 'ioredis-mock'

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

  beforeEach(async function () {
    await mockConfig(config = { baseUrls: ['http://ui-server/'] })
    await mockRedis()
    mockFetch({
      'http://ui-server': {
        '/manifest.json': generateSimpleViteManifest({ 'example.js': 'test' }),
        '/example.js': ''
      }
    })
    app = await injectApp()
  })

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

  it('change version when salt changes', async function () {
    const pubClient = new RedisMock()
    let runUpdate
    await import('../src/version.js').then(async ({ updateVersionProcessor }) => {
      runUpdate = updateVersionProcessor
    })
    await runUpdate(pubClient)
    await runUpdate(pubClient)

    const response = await app.inject({ url: '/manifests' })
    expect(response.statusCode).to.equal(200)
    expect(response.headers.version).to.equal('1916675216')

    // update salt
    config.salt = '1'

    // need to process two times to actually trigger the update
    await runUpdate(pubClient)
    await runUpdate(pubClient)

    const responseAfterUpdate = await app.inject({ url: '/manifests' })
    expect(responseAfterUpdate.statusCode).to.equal(200)
    expect(responseAfterUpdate.headers.version).to.equal('1916675216-1')
  })
})