import { Request, Response } from 'express';
import { AIService } from '../services/ai.service';
import { sendSuccess, sendError } from '../utils/apiResponse';
import logger from '../utils/logger';

export class AIController {
    static async chat(req: any, res: Response) {
        try {
            const { systemInstruction, userMessage, sessionId } = req.body;

            if (!userMessage) {
                return sendError(res, 'User message is required', 400);
            }

            const userId = req.user.userId;
            const result = await AIService.chat(userId, systemInstruction, userMessage, sessionId);
            return sendSuccess(res, result);

        } catch (error: any) {
            console.error('AI Chat Error:', error); // Keep console log for now as AI errors can be tricky

            let errorMessage = 'Failed to generate AI response';
            if (error.message?.includes('API key') || error.message === 'AI service not configured') {
                errorMessage = 'AI service authentication failed';
                if (error.message === 'AI service not configured') {
                    return sendError(res, errorMessage, 500);
                }
            } else if (error.message?.includes('quota')) {
                errorMessage = 'AI service quota exceeded';
            } else if (error.message) {
                errorMessage = error.message;
            }

            logger.error('Error in chat', { error: errorMessage });
            return sendError(res, errorMessage, 500);
        }
    }

    static async clearChat(req: any, res: Response) {
        try {
            const userId = req.user.userId;
            const sessionId = req.params.sessionId || 'default';
            await AIService.clearChat(userId, sessionId);
            return sendSuccess(res, null);
        } catch (error) {
            logger.error('Error in clearChat', { error });
            return sendError(res, 'Failed to clear chat session', 500);
        }
    }
}
