import { NextRequest, NextResponse } from 'next/server';
import { adminDb } from '@/lib/firebase-admin';
import { COLLECTIONS } from '@/types/firestore';
import * as admin from 'firebase-admin';
import { classifyQuery, QueryType } from '@/lib/ai/queryRouter';
import { verifyMember } from '@/lib/auth-middleware';

export async function POST(req: NextRequest) {
    try {
        const body = await req.json();
        const { question, companyId, productId, forceType } = body;

        // 인증 체크: Firebase ID Token 검증
        const authResult = await verifyMember(req);
        if (authResult instanceof NextResponse) return authResult;
        const { uid } = authResult;

        if (!question) {
            return NextResponse.json({ error: 'question은 필수입니다.' }, { status: 400 });
        }

        // ─── Query Router: 질의 유형 분류 ───────────────────────────
        const queryType: QueryType = forceType ?? classifyQuery(question, { companyId, productId });

        // AMBIGUOUS: 사용자가 유형을 선택하도록 프론트에 위임
        if (queryType === 'AMBIGUOUS') {
            return NextResponse.json({
                queryType: 'AMBIGUOUS',
                message: '질의 유형을 선택해 주세요.',
            }, { status: 200 });
        }

        // ─── A형: 수치 조회형 (TABLE_QUERY) ─────────────────────────
        // 즉시 Firestore insurance_tables 쿼리 후 응답
        if (queryType === 'TABLE_QUERY') {
            if (!companyId || !productId) {
                return NextResponse.json(
                    { error: '보험료 조회에는 회사와 상품 선택이 필요합니다.' },
                    { status: 400 }
                );
            }
            // TODO (Step 9): insurance_tables 구현 후 실제 쿼리로 교체
            return NextResponse.json({
                queryType: 'TABLE_QUERY',
                answer: '⚠️ 보험료 테이블 DB가 아직 구축 중입니다. (Step 9에서 완성 예정)',
                isPlaceholder: true,
            }, { status: 200 });
        }

        // ─── B형: 횡단 검색형 (VECTOR_SEARCH) ───────────────────────
        // /api/ai/vector-search 엔드포인트로 위임
        if (queryType === 'VECTOR_SEARCH') {
            const vsRes = await fetch(`${req.nextUrl.origin}/api/ai/vector-search`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': req.headers.get('Authorization') || '',
                },
                body: JSON.stringify({ question }),
            });
            const vsData = await vsRes.json();
            return NextResponse.json({ queryType: 'VECTOR_SEARCH', ...vsData }, { status: vsRes.status });
        }

        // ─── C형: 심층 분석형 (DEEP_QUERY) ──────────────────────────
        // 회사+상품 필수
        if (!companyId || !productId) {
            return NextResponse.json(
                { error: '심층 약관 분석에는 회사와 상품 선택이 필요합니다.' },
                { status: 400 }
            );
        }

        // Job 생성 → Cloud Functions 비동기 처리
        const expireAt = new Date();
        expireAt.setMinutes(expireAt.getMinutes() + 10);

        const newJob = {
            userId: uid,
            status: 'pending',
            type: 'pdf_query',
            queryType: 'DEEP_QUERY',
            question,
            companyId,
            productId,
            createdAt: admin.firestore.FieldValue.serverTimestamp(),
            updatedAt: admin.firestore.FieldValue.serverTimestamp(),
            expireAt: admin.firestore.Timestamp.fromDate(expireAt),
        };

        const jobRef = await adminDb.collection(COLLECTIONS.JOBS).add(newJob);

        return NextResponse.json({
            queryType: 'DEEP_QUERY',
            jobId: jobRef.id,
        }, { status: 200 });

    } catch (error: any) {
        console.error('AI Query Router Error:', error);
        return NextResponse.json({ error: error.message }, { status: 500 });
    }
}
