/*
 *
 * @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 { configMap } from '../config_map.js'
import * as cache from '../cache.js'
import { getRedisKey } from '../util.js'

async function fetchMergedMetadata () {
  const metadata = await Promise.all(configMap.urls.map(async url => {
    const { origin } = new URL(url)
    try {
      const response = await fetch(new URL('meta.json', origin), { cache: 'no-store' })
      if (!response.ok) return
      return response.json()
    } catch (e) {
      // unhandled
    }
  }))

  metadata.push({
    id: 'ui-middleware',
    name: 'UI Middleware',
    buildDate: process.env.BUILD_TIMESTAMP,
    commitSha: process.env.CI_COMMIT_SHA,
    version: process.env.APP_VERSION
  })

  // only return when contains data
  return metadata.filter(Boolean)
}

export default async function metadataPlugin (fastify) {
  fastify.get('/meta', async (req, res) => {
    const mergedMetadata = await cache.get(getRedisKey({ version: res.version, name: 'mergedMetadata' }), async () => [await fetchMergedMetadata()])
    res.send(mergedMetadata)
  })
}