import { NextRequest, NextResponse } from 'next/server';
import { GoogleGenerativeAI } from '@google/generative-ai';
import { adminDb } from '@/lib/firebase-admin';
import { COLLECTIONS } from '@/types/firestore';
import { decrypt } from '@/utils/encryption';
import { verifyMember } from '@/lib/auth-middleware';

export async function POST(req: NextRequest) {
    try {
        const { docId, promptType, text: providedText } = await req.json();

        // 1. Firebase ID Token 검증
        const authResult = await verifyMember(req);
        if (authResult instanceof NextResponse) return authResult;
        const { uid } = authResult;

        // 2. Fetch User's Encrypted API Key
        const userRef = adminDb.collection(COLLECTIONS.USERS).doc(uid);
        const userDoc = await userRef.get();
        const userData = userDoc.data();

        const encryptedKey = userData?.aiSettings?.geminiApiKey;
        if (!encryptedKey) {
            return NextResponse.json({ error: 'Gemini API Key가 등록되지 않았습니다.' }, { status: 400 });
        }

        const apiKey = decrypt(encryptedKey);

        // 3. Fetch Document Content (Only if text is NOT provided or needed)
        // For 'refine', we use providedText. For others, we need doc content.
        let documentTitle = '';
        let documentContent = '';

        if (promptType !== 'refine' || !providedText) {
            const docRef = adminDb.collection(COLLECTIONS.DOCUMENTS).doc(docId);
            const docSnap = await docRef.get();
            if (!docSnap.exists) {
                return NextResponse.json({ error: '문서를 찾을 수 없습니다.' }, { status: 404 });
            }
            const document = docSnap.data();
            documentTitle = document?.title || '';
            documentContent = document?.content || '';
        }

        // 4. Call Gemini API
        const genAI = new GoogleGenerativeAI(apiKey);
        const model = genAI.getGenerativeModel({ model: "gemini-2.5-flash" });

        let systemPrompt = "당신은 보험 전문가들의 지식 공유 플랫폼 '인슈위키'의 AI 어시스턴트입니다. ";
        let prompt = '';

        if (promptType === 'summarize') {
            systemPrompt += "다음 문서를 핵심 위주로 3~5문장으로 요약해주세요. 전문용어를 적절히 사용하되 명확하게 설명하세요.";
            prompt = `${systemPrompt}\n\n[문서 제목]: ${documentTitle}\n\n[문서 내용]:\n${documentContent}`;
        } else if (promptType === 'structure') {
            systemPrompt += "다음 마크다운 문서의 구조를 개선하여 가독성을 높여주세요. 목차(TOC)가 잘 드러나도록 계층 구조를 정리하세요.";
            prompt = `${systemPrompt}\n\n[문서 제목]: ${documentTitle}\n\n[문서 내용]:\n${documentContent}`;
        } else if (promptType === 'compare') {
            systemPrompt += "다음 문서의 내용을 분석하여 비교표(Comparison Table)를 마크다운 표 형태로 작성해주세요. 상품, 조건, 특약 등 핵심 항목별로 비교하세요.";
            prompt = `${systemPrompt}\n\n[문서 제목]: ${documentTitle}\n\n[문서 내용]:\n${documentContent}`;
        } else if (promptType === 'mask') {
            systemPrompt += "다음 문서에서 개인정보(PII)를 식별하고 마스킹 처리해주세요. 주민등록번호(***-***-****), 전화번호(***-****-****), 이메일, 주소, 계좌번호 등을 [개인정보 마스킹]으로 대체하고, 원문과 마스킹된 버전을 함께 제시하세요.";
            prompt = `${systemPrompt}\n\n[문서 제목]: ${documentTitle}\n\n[문서 내용]:\n${documentContent}`;
        } else if (promptType === 'coach') {
            systemPrompt += "다음 상담 기록을 전문적으로 분석하여 피드백을 제공해주세요. 잘한 점, 개선할 점, 구체적인 개선 제안을 포함하세요. 보험 설계사 코칭 관점에서 작성하세요.";
            prompt = `${systemPrompt}\n\n[문서 제목]: ${documentTitle}\n\n[문서 내용]:\n${documentContent}`;
        } else if (promptType === 'refine') {
            // [NEW] Refine logic - Strengthened for transformation (Rewrite & Auto-Format)
            // Added Few-Shot Examples to force compliance
            systemPrompt = `당신은 구어체를 문어체로 완벽하게 변환하는 전문 교정 AI입니다. 아래 텍스트를 보고서나 위키 형식에 맞게 '재작성(Rewrite)'하세요.

[필수 지침]
1. '1번', '첫째' 등의 구어체 번호를 마크다운 리스트(1., -)로 변환하여 구조화하세요.
2. **계층형 번호(예: '2의 1', '2-1번')는 2.1. 형식으로 변환하여 들여쓰기와 함께 표현하세요.**
3. 단순 교정이 아니라, 문장 구조를 완전히 뜯어고쳐 전문적인 글로 바꾸세요.
4. 구어체 말투(요, 죠, 는데요 등)를 완전히 제거하고 서술어(한다, 함, 임)로 끝맺으세요.
5. 부가 설명 없이 오직 다듬어진 텍스트만 출력하세요.

[예시]
Input: 1번 오늘 점심은 짜장면 2번 저녁은 굶음 2의 1번 돈이 없어서
Output:
1. 오늘 점심은 짜장면
2. 저녁은 굶음
    2.1. 돈이 없어서`;
            prompt = `${systemPrompt}\n\n[원본 구어체 텍스트]:\n${providedText}`;
        } else {
            systemPrompt += "다음 문서를 분석하여 중요한 정보를 정리해주세요.";
            prompt = `${systemPrompt}\n\n[문서 제목]: ${documentTitle}\n\n[문서 내용]:\n${documentContent}`;
        }

        const result = await model.generateContent(prompt);
        const response = await result.response;
        const text = response.text();

        return NextResponse.json({ text });
    } catch (error: any) {
        console.error('AI Summarize Error:', error);
        return NextResponse.json({ error: error.message || 'AI 처리 중 오류가 발생했습니다.' }, { status: 500 });
    }
}
