import { Injectable, OnModuleInit } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Prompt, PromptDocument } from './prompts.model';
import { PromptType } from './prompts.enum';
import { getCachedPrompts, setCachedPrompts } from './prompts.cache';

@Injectable()
export class PromptsService implements OnModuleInit {
	constructor(
		@InjectModel(Prompt.name) private promptModel: Model<PromptDocument>
	) {
		console.log('PromptsService: constructor - initializing PromptsService');
	}

	async onModuleInit() {
		await this.updatePromptsCache();
	}

	private async getPromptsFromDb(): Promise<Map<PromptType, string>> {
		console.log('PromptsService: getPromptsFromDb - retrieving prompts from database');
		try {
			const prompts = await this.promptModel.find().exec();
			console.log(`PromptsService: getPromptsFromDb - found ${prompts.length} prompts`);

			const promptsMap = new Map<PromptType, string>();
			prompts.forEach(prompt => {
				promptsMap.set(prompt.type, prompt.text);
			});

			return promptsMap;
		} catch (error) {
			console.error('PromptsService: getPromptsFromDb - error retrieving prompts:', error);
			throw error;
		}
	}

	async getPromptByType(type: PromptType): Promise<string | null> {
		console.log(`PromptsService: getPromptByType - retrieving prompt with type: ${type}`);

		const cachedPrompts = getCachedPrompts();
		if (cachedPrompts && cachedPrompts.has(type)) {
			const promptText = cachedPrompts.get(type);
			console.log(`PromptsService: getPromptByType - found prompt in cache for type: ${type}`);
			return promptText || null;
		}

		console.log(`PromptsService: getPromptByType - prompt not found in cache for type: ${type}`);
		return null;
	}

	async updatePromptsCache(): Promise<void> {
		console.log('PromptsService: updatePromptsCache - updating prompts cache');
		const prompts = await this.getPromptsFromDb();
		setCachedPrompts(prompts);
		console.log(`PromptsService: updatePromptsCache - cached ${prompts.size} prompts`);
	}
}

