import Fastify from 'fastify';
import * as dotenv from 'dotenv';
import recommendationsRoute from './routes/recommendations.js';
import feedbackRoute from './routes/feedback.js';

// Load .env.local first, then .env.
// dotenv 17+ supports array of paths, where the first path has the highest priority.
// Env vars set on the container (system) will take precedence over both.
dotenv.config({ path: ['.env.local', '.env'] });

const fastify = Fastify({ logger: true });

// CORS — allow frontend dev server and production
fastify.addHook('onRequest', async (_req, reply) => {
  reply.header('Access-Control-Allow-Origin', '*');
  reply.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
  reply.header('Access-Control-Allow-Headers', 'Content-Type');
});

fastify.options('*', async (_req, reply) => {
  return reply.send();
});

// Body parsing is included in Fastify by default for JSON
await fastify.register(recommendationsRoute);
await fastify.register(feedbackRoute);

const port = Number(process.env['PORT'] ?? 3000);

try {
  await fastify.listen({ port, host: '0.0.0.0' });
  console.log(`Backend listening on http://localhost:${port}`);
} catch (err) {
  fastify.log.error(err);
  process.exit(1);
}
