import { NextRequest, NextResponse } from 'next/server';
import { adminDb } from '@/lib/firebase-admin';
import { COLLECTIONS } from '@/types/firestore';
import { verifyAdmin } from '@/lib/auth-middleware';

export async function POST(req: NextRequest) {
    const authResult = await verifyAdmin(req);
    if (authResult instanceof NextResponse) return authResult;

    try {
        const { companyId, productId } = await req.json();

        if (!companyId || !productId) {
            return NextResponse.json({ error: 'Missing companyId or productId' }, { status: 400 });
        }

        // 특정 회사/상품에 대한 캐시 일괄 무효화
        const cacheQuery = await adminDb.collection(COLLECTIONS.GEMINI_FILE_CACHE)
            .where('companyId', '==', companyId)
            .where('productId', '==', productId)
            .get();

        const batch = adminDb.batch();
        let deletedCount = 0;

        cacheQuery.forEach((doc: any) => {
            batch.delete(doc.ref);
            deletedCount++;
        });

        if (deletedCount > 0) {
            await batch.commit();
        }

        return NextResponse.json({ success: true, deletedCount }, { status: 200 });

    } catch (error: any) {
        console.error('Cache Invalidation Error:', error);
        return NextResponse.json({ error: error.message }, { status: 500 });
    }
}
