import { FastifyReply, FastifyRequest } from 'fastify';
import { APIKeyService } from '../../services/APIKeyService';
import { App } from '../../entities/app/_App';
import { User } from '../../entities/user/_User';
import { APIKey } from '../../entities/apikey/_APIKey';
import crypto from 'crypto';

export class APIKeyController {
    private apiKeyService: APIKeyService;
    constructor(apiKeyService: APIKeyService) {
        this.apiKeyService = apiKeyService;
    }

    async getOrCreateApiKey(request: FastifyRequest<{ Body: { userId: number; appId: number } }>, reply: FastifyReply) {
        try {
            const { userId, appId } = request.body;
            if (!userId || !appId) {
                return reply.status(400).send({ error: 'userId and appId are required' });
            }

            let apiKeyEntity = await this.apiKeyService.getAPIKeyEntityForUserAndApp(userId, appId);
            if (!apiKeyEntity) {
                // Generate a new API key
                const key = crypto.randomBytes(32).toString('hex');
                const em = request.em;

                // Check if user exists
                const user = await em.findOne(User, { id: userId });
                if (!user) {
                    return reply.status(404).send({ error: `User with ID ${userId} not found` });
                }

                // Check if app exists
                const app = await em.findOne(App, { id: appId });
                if (!app) {
                    return reply.status(404).send({ error: `App with ID ${appId} not found` });
                }

                // Create new API key
                apiKeyEntity = new APIKey();
                apiKeyEntity.key = key;
                apiKeyEntity.user = user;
                apiKeyEntity.app = app;

                try {
                    await em.persistAndFlush(apiKeyEntity);
                } catch (dbError) {
                    console.error('Database error while creating API key:', dbError);
                    return reply.status(500).send({ error: 'Failed to create API key in database' });
                }
            }

            return reply.send({ apiKey: apiKeyEntity.key });
        } catch (error) {
            console.error('Error in getOrCreateApiKey:', error);
            return reply.status(500).send({ error: 'Internal server error while processing API key request' });
        }
    }
} 