import Fastify from 'fastify';
import cors from '@fastify/cors';
import jwt from '@fastify/jwt';
import cookie from '@fastify/cookie';
import { healthRoutes } from './routes/health.js';
import { categoryRoutes } from './routes/categories.js';
import { recipeRoutes } from './routes/recipes.js';
import { noteRoutes } from './routes/notes.js';
import { shoppingRoutes } from './routes/shopping.js';
import { tagRoutes } from './routes/tags.js';
import { imageRoutes } from './routes/images.js';
import { botRoutes } from './routes/bot.js';
import { ogScrapeRoutes } from './routes/og-scrape.js';
import { authRoutes } from './routes/auth.js';
import { householdRoutes } from './routes/households.js';

export async function buildApp() {
  const app = Fastify({ logger: true });

  await app.register(cors, { origin: true });
  await app.after();

  // Register JWT plugin (though we handle JWT manually in auth service)
  await app.register(jwt, {
    secret: process.env.JWT_SECRET || 'your-super-secret-jwt-key-change-in-production',
  });
  await app.after();

  // Register Cookie plugin for refresh tokens
  await app.register(cookie, {
    secret: process.env.COOKIE_SECRET || 'your-super-secret-cookie-key-change-in-production',
    parseOptions: {},
  });
  await app.after();

  await app.register(healthRoutes);
  await app.after();

  await app.register(categoryRoutes);
  await app.after();

  await app.register(recipeRoutes);
  await app.after();

  await app.register(noteRoutes);
  await app.after();

  await app.register(shoppingRoutes);
  await app.after();

  await app.register(tagRoutes);
  await app.after();

  await app.register(imageRoutes);
  await app.after();

  await app.register(botRoutes);
  await app.after();

  await app.register(ogScrapeRoutes);
  await app.after();

  await app.register(authRoutes);
  await app.after();

  await app.register(householdRoutes);
  await app.after();

  return app;
}
