import express from 'express'
import helmet from 'helmet'
import { httpLogger } from './logger.js'
import { metricsMiddleware } from '@open-xchange/metrics'
import swaggerUi from 'swagger-ui-express'
import yaml from 'js-yaml'
import fs from 'fs'

import versionMiddleware from './middlewares/version.js'
import loadFromCacheMiddleware from './middlewares/load-from-cache.js'
import loadFromUIServersMiddleware from './middlewares/load-from-server.js'
import saveToCacheMiddleware from './middlewares/save-to-cache.js'
import finalHandlerMiddleware from './middlewares/final-handler.js'

import health from './routes/health.js'
import manifestsRouter from './routes/manifests.js'
import metadataRouter from './routes/metadata.js'
import redirectsRouter from './routes/redirects.js'

const swaggerDocument = yaml.load(fs.readFileSync('./src/swagger.yaml', 'utf8'))

const metricsMiddlewareInstance = metricsMiddleware()

export function createApp () {
  const app = express()
  app.use(express.urlencoded({ extended: true }))

  // Application-level middleware
  app.use(httpLogger)
  app.use(helmet({
    contentSecurityPolicy: false,
    crossOriginEmbedderPolicy: false,
    originAgentCluster: false,
    crossOriginOpenerPolicy: { policy: 'same-origin-allow-popups' }
  }))
  app.use(health)
  app.use(metricsMiddlewareInstance)
  app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument))
  app.use('/swagger.json', (req, res) => res.json(swaggerDocument))
  app.timeout = 30000

  app.use(versionMiddleware)
  app.use(loadFromCacheMiddleware)

  app.use(manifestsRouter)
  app.use(metadataRouter)
  app.use(redirectsRouter)

  app.use(loadFromUIServersMiddleware)
  app.use(saveToCacheMiddleware)
  app.use(finalHandlerMiddleware)

  return app
}