import { EntityManager } from '@mikro-orm/core';
import { APIKeyRepository } from '../repositories/APIKeyRepository';
import { APIKey } from '../entities/apikey/_APIKey';

export class APIKeyService {
    private apiKeyRepository: APIKeyRepository;
    private em: EntityManager;

    constructor(em: EntityManager) {
        this.em = em;
        this.apiKeyRepository = this.em.getRepository(APIKey);
    }

    async getAPIKeyForUser(userId: number): Promise<string | null> {
        const apiKey = await this.apiKeyRepository.findAPIKeyByUserId(userId);
        return apiKey ? apiKey.key : null;
    }

    async getAPIKeyForUserAndApp(userId: number, appId: number): Promise<string | null> {
        const apiKey = await this.apiKeyRepository.findOne({ user: userId, app: appId });
        return apiKey ? apiKey.key : null;
    }

    async getAPIKeyEntityForUserAndApp(userId: number, appId: number): Promise<APIKey | null> {
        return this.apiKeyRepository.findOne({ user: userId, app: appId });
    }
}
