/**
 * @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 { injectApp, mockRedis } from './util.js'
import { expect } from 'chai'
import * as td from 'testdouble'
import RedisMock from 'ioredis-mock'

describe('Responses contain custom headers', function () {
  let client
  let app

  beforeEach(async function () {
    client = (await mockRedis()).client
    await Promise.all([
      client.set('ui-middleware:versionInfo', JSON.stringify({ version: '123456' })),
      client.set('ui-middleware:123456:mergedMetadata', JSON.stringify([
        { name: 'sample-service', version: '1.0' },
        {
          id: 'ui-middleware',
          name: 'UI Middleware',
          buildDate: '0123456789',
          commitSha: '0123456789abcdef',
          version: '4.2'
        }
      ]))
    ])
    app = await injectApp()
  })

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

  it('has own metadata', async function () {
    const response = await app.inject({ url: '/meta' })
    expect(response.statusCode).to.equal(200)
    expect(response.json()).to.deep.contain({
      id: 'ui-middleware',
      name: 'UI Middleware',
      buildDate: '0123456789',
      commitSha: '0123456789abcdef',
      version: '4.2'
    })
  })

  it('has metadata from another ui service if available', async function () {
    const response = await app.inject({ url: '/meta' })
    expect(response.statusCode).to.equal(200)
    expect(response.json()).to.deep.contain({
      name: 'sample-service',
      version: '1.0'
    })
  })

  it('has updated metadata if config is updated', async function () {
    const response = await app.inject({ url: '/meta' })
    expect(response.json()).to.have.length(2)

    client.set('ui-middleware:123457:mergedMetadata', JSON.stringify([
      { name: 'sample-service', version: '2.0' }
    ]))
    const response2 = await app.inject({ url: '/meta', headers: { version: '123457' } })
    expect(response2.json()).to.have.length(1)
  })
})