/*
 *
 * @copyright Copyright (c) OX Software 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 { expect } from 'chai'
import { generateSimpleViteManifest, injectApp, mockConfig, mockFetch } from '../spec/util.js'
import * as td from 'testdouble'
import { getRedisKey } from '../src/util.js'
import zlib from 'node:zlib'

describe('File caching service', function () {
  let app, pubClient

  beforeEach(async function () {
    await mockConfig({ 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' } })
      }
    })
    await import('../src/redis.js').then(({ client, createClient }) => {
      pubClient = createClient()
      return client.flushdb()
    })
    await import('../src/version.js').then(async ({ updateVersionProcessor }) => {
      await updateVersionProcessor(pubClient)
      await updateVersionProcessor(pubClient)
    })
    app = await injectApp()
  })

  afterEach(async function () {
    td.reset()
  })

  it('caches manifest data', async function () {
    const response = await app.inject({ url: '/manifests' })
    expect(response.statusCode).to.equal(200)
    const version = response.headers.version

    const { client } = await import('../src/redis.js')
    expect(await client.get(getRedisKey({ version, name: 'viteManifests' }))).to.equal('{"index.html":{"file":"index.html","meta":{"baseUrl":"http://ui-server/"}}}')
    const redisData = await client.getBuffer(getRedisKey({ version, name: 'oxManifests:body' }))
    expect(zlib.brotliDecompressSync(redisData || '').toString()).to.equal('[]')
  })

  it('caches html files', async function () {
    const response = await app.inject({ url: '/index.html' })
    expect(response.statusCode).to.equal(200)
    const version = response.headers.version

    const { client } = await import('../src/redis.js')
    const body = (await client.getBuffer(getRedisKey({ version, name: '/index.html:body' }))) || ''
    expect(body.toString()).to.equal('<html><head></head><body>it\'s me</body></html>')
    const meta = await client.get(getRedisKey({ version, name: '/index.html:meta' }))
    expect(meta).to.equal('{"headers":{"content-type":"text/html","dependencies":false}}')
  })

  it('serves files from redis and stores them in local cache', async function () {
    const version = '12345'
    const { client } = await import('../src/redis.js')
    await client.set(getRedisKey({ version, name: '/demo.js:meta' }), '{"headers":{"content-type":"application/javascript","dependencies":false}}')
    await client.set(getRedisKey({ version, name: '/demo.js:body' }), 'console.log("Demo")')

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

    // just for testing purposes, delete the keys from redis to make sure, it is served from local cache
    await client.del(getRedisKey({ version, name: '/demo.js:meta' }))
    await client.del(getRedisKey({ version, name: '/demo.js:body' }))

    const response2 = await app.inject({ url: '/demo.js', headers: { version } })
    expect(response2.statusCode).to.equal(200)
  })
})