import Fastify from 'fastify';
import cors from '@fastify/cors';
import helmet from '@fastify/helmet';
import { config } from './config/index.js';
import { registerProcessorRoutes } from './processor/routes.js';
import { registerApiRoutes } from './api/routes.js';
import { createPool } from './data/db.js';
import { createRedis } from './data/redis.js';

const app = Fastify({
  logger: {
    level: config.logLevel,
    transport: config.nodeEnv === 'development'
      ? { target: 'pino-pretty' }
      : undefined,
  },
});

async function start() {
  await app.register(cors, { origin: config.corsOrigin });
  await app.register(helmet);

  // Data layer
  const pool = createPool(config.databaseUrl);
  const redis = createRedis(config.redisUrl);

  // Decorate fastify instance
  app.decorate('pool', pool);
  app.decorate('redis', redis);
  app.decorate('config', config);

  // Routes
  await registerProcessorRoutes(app);
  await registerApiRoutes(app);

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

  await app.listen({ port: config.port, host: '0.0.0.0' });
  app.log.info(`dd0c/drift SaaS listening on :${config.port}`);
}

start().catch((err) => {
  console.error('Failed to start:', err);
  process.exit(1);
});

export { app };
