import { FastifyPluginAsync, FastifyRequest, FastifyReply } from 'fastify';
import { APIKeyService } from '../services/APIKeyService';
import { APIKeyController } from '../http/controllers/APIKeyController';

const apiKeyRoutes: FastifyPluginAsync = async (app) => {
    app.post('/generate', async (request: FastifyRequest<{ Body: { userId: number; appId: number } }>, reply: FastifyReply) => {
        const apiKeyService = new APIKeyService(request.em);
        const controller = new APIKeyController(apiKeyService);
        return controller.getOrCreateApiKey(request, reply);
    });

    app.post('/get', async (request: FastifyRequest<{ Body: { userId: number; appId: number } }>, reply: FastifyReply) => {
        const apiKeyService = new APIKeyService(request.em);
        const apiKey = await apiKeyService.getAPIKeyForUserAndApp(request.body.userId, request.body.appId);
        if (!apiKey) return reply.send({ apiKey: null });
        return reply.send({ apiKey });
    });
};

export default apiKeyRoutes; 