import Fastify from 'fastify';
import type { HealthCheckResponse } from '@house-plan-maker/shared';
import prismaPlugin from './plugins/prisma.js';
import errorHandlerPlugin from './plugins/error-handler.js';
import apartmentRoutes from './routes/apartments.js';
import roomRoutes from './routes/rooms.js';
import elementRoutes from './routes/elements.js';

const PORT = parseInt(process.env.PORT ?? '3001', 10);
const HOST = process.env.HOST ?? '0.0.0.0';

const server = Fastify({
  logger: true,
});

// Plugins
server.register(prismaPlugin);
server.register(errorHandlerPlugin);

// Routes
server.register(apartmentRoutes);
server.register(roomRoutes);
server.register(elementRoutes);

server.get('/api/health', async (_request, _reply): Promise<HealthCheckResponse> => {
  return {
    status: 'ok',
    timestamp: new Date().toISOString(),
  };
});

async function start() {
  try {
    await server.listen({ port: PORT, host: HOST });
    server.log.info(`Server listening on http://${HOST}:${PORT}`);
  } catch (err) {
    server.log.error(err);
    process.exit(1);
  }
}

start();
