import { NextRequest, NextResponse } from 'next/server';
import { getAuth } from 'firebase-admin/auth';
import { getFirebaseAdmin } from '@/lib/firebase-admin';
import { FieldValue, Timestamp } from 'firebase-admin/firestore';
import { ADMIN_EMAILS } from '@/lib/constants';

export async function POST(req: NextRequest) {
    try {
        const authHeader = req.headers.get('Authorization');
        if (!authHeader?.startsWith('Bearer ')) {
            return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
        }
        const idToken = authHeader.split('Bearer ')[1];
        getFirebaseAdmin();
        let userEmail: string | undefined;
        try {
            const decoded = await getAuth().verifyIdToken(idToken);
            userEmail = decoded.email;
        } catch {
            return NextResponse.json({ error: 'Unauthorized: Invalid token' }, { status: 401 });
        }
        if (!userEmail || !ADMIN_EMAILS.includes(userEmail)) {
            return NextResponse.json({ error: 'Forbidden: Admin only' }, { status: 403 });
        }

        const { productId } = await req.json();
        if (!productId) {
            return NextResponse.json({ error: 'productId required' }, { status: 400 });
        }

        const db = getFirebaseAdmin().firestore();

        // Phase 1에서 문서 ID가 productId_effectiveDate로 변경됨 → where 쿼리로 조회
        const metaQuery = await db.collection('insurance_metadata')
            .where('productId', '==', productId)
            .where('isActive', '==', true)
            .orderBy('createdAt', 'desc')
            .limit(1)
            .get();

        if (metaQuery.empty) {
            return NextResponse.json({ error: 'Product not found' }, { status: 404 });
        }

        const meta = metaQuery.docs[0].data();

        // 기존 staging 데이터 정리 (이전 재인덱싱 잔여 데이터 제거)
        const existingStagingQuery = await db.collection('insurance_chunks_staging')
            .where('productId', '==', productId)
            .get();

        if (!existingStagingQuery.empty) {
            const BATCH_LIMIT = 400;
            const stagingDocs = existingStagingQuery.docs;
            for (let i = 0; i < stagingDocs.length; i += BATCH_LIMIT) {
                const cleanupBatch = db.batch();
                stagingDocs.slice(i, i + BATCH_LIMIT).forEach((doc: FirebaseFirestore.QueryDocumentSnapshot) => cleanupBatch.delete(doc.ref));
                await cleanupBatch.commit();
            }
            console.log(`기존 staging 청크 ${existingStagingQuery.size}개 정리 완료 (productId: ${productId})`);
        }

        // CL-7: 해당 productId의 query_cache 무효화
        const cacheQuery = await db.collection('query_cache')
            .where('productId', '==', productId)
            .get();
        if (!cacheQuery.empty) {
            const BATCH_LIMIT = 400;
            const cacheDocs = cacheQuery.docs;
            for (let i = 0; i < cacheDocs.length; i += BATCH_LIMIT) {
                const cacheBatch = db.batch();
                cacheDocs.slice(i, i + BATCH_LIMIT).forEach((doc: FirebaseFirestore.QueryDocumentSnapshot) => cacheBatch.delete(doc.ref));
                await cacheBatch.commit();
            }
            console.log(`query_cache ${cacheQuery.size}개 무효화 완료 (productId: ${productId})`);
        }

        // CL-9: 해당 productId의 insurance_appendices 정리
        const appendicesQuery = await db.collection('insurance_appendices')
            .where('productId', '==', productId)
            .get();
        if (!appendicesQuery.empty) {
            const appendicesBatch = db.batch();
            appendicesQuery.docs.forEach((doc: FirebaseFirestore.QueryDocumentSnapshot) => appendicesBatch.delete(doc.ref));
            await appendicesBatch.commit();
            console.log(`insurance_appendices ${appendicesQuery.size}개 정리 완료 (productId: ${productId})`);
        }

        // 새 index_pdf job 생성 (Blue-Green 모드)
        const expireAt = new Date(Date.now() + 20 * 60 * 1000);
        const jobRef = await db.collection('jobs').add({
            type: 'index_pdf',
            status: 'pending',
            driveFileId: meta.driveFileId,
            companyId: meta.companyId,
            companyName: meta.companyName,
            productId: meta.productId,
            productName: meta.productName,
            category: meta.category,
            effectiveDate: meta.effectiveDateRange?.start || '',
            createdAt: FieldValue.serverTimestamp(),
            updatedAt: FieldValue.serverTimestamp(),
            expireAt: Timestamp.fromDate(expireAt),
            isReindex: true,
            blueGreenMode: true,
            targetCollection: 'insurance_chunks_staging',
        });

        return NextResponse.json({
            success: true,
            jobId: jobRef.id,
            cacheCleared: cacheQuery.empty ? 0 : cacheQuery.size,
            appendicesCleared: appendicesQuery.empty ? 0 : appendicesQuery.size,
        });
    } catch (error: any) {
        console.error('POST /api/admin/insurance/reindex error:', error);
        return NextResponse.json({ error: 'Internal Server Error', message: error.message }, { status: 500 });
    }
}
