/*
 *
 * @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 { config } from 'dotenv-defaults'
import { createClient, isReady, switchClient } from './redis.js'
import logger from './logger.js'
import fastify from 'fastify'
import autoLoad from '@fastify/autoload'
import { fileURLToPath } from 'node:url'
import { join, dirname } from 'node:path'
import lightship from './lightship.js'
import { updateVersionProcessor, versionInfo } from './version.js'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const pubClient = createClient('pub client')
const client = createClient('cache writer', { maxRetriesPerRequest: 1 })
switchClient(client)

client.on('connect', async () => {
  logger.debug('[Redis] cache writer connected, forcing cache update')
  // forget local version and make sure to run warmCache next time
  versionInfo.version = 'unknown'
})

config()

async function runUpdate () {
  try {
    await updateVersionProcessor(pubClient)
  } catch (err) {} finally {
    setTimeout(() => runUpdate(), Number(process.env.CACHE_TTL))
  }
}
runUpdate()

lightship.queueBlockingTask(isReady(client))

const app = fastify({})
app.register(autoLoad, { dir: join(__dirname, 'plugins') })
app.addHook('onReady', () => { lightship.signalReady() })

try {
  // Binds and listens for connections on the specified host and port
  await app.listen({ host: '::', port: Number(process.env.PORT) })
} catch (err) {
  logger.error(err)
  await lightship.shutdown()
}

lightship.registerShutdownHandler(async () => {
  logger.info('[Service] Shutting down...')
  await Promise.all([
    client.quit(),
    pubClient.quit()
  ])
  await app.close()
})