import { FastifyPluginAsync } from 'fastify';
import userRoutes from './apps/_app/routes/UserRoutes';
import canvasRoutes from './apps/canvas-api/canvasRouter';
import apiKeyRoutes from './apps/_app/routes/APIKeyRoutes';
import appRoutes from './apps/_app/routes/AppRoutes';

const routesPlugin: FastifyPluginAsync = async (app) => {
    try {
        ///////////////////////////////////////
        // TODO: Define routes in separate list
        await app.register(userRoutes, { prefix: '/app/users' });
        await app.register(apiKeyRoutes, { prefix: '/app/apikey' });
        await app.register(canvasRoutes, { prefix: '/canvas-api' });
        await app.register(appRoutes, { prefix: '/app' });

        app.setErrorHandler((error, request, reply) => {
            if (!reply.sent) {
                // Ensure it's not already sent
                reply.code(500).send({ error: 'Server error' });
            }
        });

        app.setNotFoundHandler((request, reply) => {
            reply.code(404).send({ message: 'Route not found' });
        });

        // TODO: catch-all routes here or not?
    } catch (error) {
        app.log.error(error, 'Failed to register routes');
        throw error;
    }
};

export default routesPlugin;
