import Fastify, { type FastifyInstance } from 'fastify'
import type { Config } from './config.ts'
import type { Db } from './db/database.ts'

export function buildApp(config: Config, db: Db): FastifyInstance {
  const app = Fastify({
    logger: {
      level: config.NODE_ENV === 'production' ? 'info' : 'debug',
      // Ne jamais journaliser les cookies ni les en-têtes d'authentification.
      redact: ['req.headers.cookie', 'req.headers.authorization', 'req.headers["stripe-signature"]'],
    },
    trustProxy: config.TRUST_PROXY === 'false' ? false : config.TRUST_PROXY,
    bodyLimit: 1024 * 1024,
  })

  // La fermeture de l'application libère aussi le pool de connexions MariaDB.
  app.addHook('onClose', async () => {
    await db.destroy()
  })

  app.get('/api/health', async () => ({ status: 'ok' }))

  return app
}
