import { NextRequest, NextResponse } from 'next/server';
import { adminDb } from '@/lib/firebase-admin';
import { verifyMember } from '@/lib/auth-middleware';
import { getChoseong } from '@/lib/utils/hangul';

export async function GET(req: NextRequest) {
    try {
        const authResult = await verifyMember(req);
        if (authResult instanceof NextResponse) return authResult;

        const q = req.nextUrl.searchParams.get('q')?.trim() ?? '';
        if (!q) {
            return NextResponse.json([], { status: 200 });
        }

        const qChoseong = getChoseong(q);

        const snapshot = await adminDb
            .collection('insurance_metadata')
            .where('isActive', '==', true)
            .get();

        const results: Array<{
            productId: string;
            productName: string;
            companyName: string;
            generationType: string | undefined;
        }> = [];

        for (const doc of snapshot.docs) {
            const data = doc.data();
            const productName: string = data.productName ?? '';
            const companyName: string = data.companyName ?? '';

            const matchesExact =
                productName.includes(q) || companyName.includes(q);
            const matchesChoseong =
                getChoseong(productName).includes(qChoseong) ||
                getChoseong(companyName).includes(qChoseong);

            if (matchesExact || matchesChoseong) {
                results.push({
                    productId: data.productId,
                    productName,
                    companyName,
                    generationType: data.generationType,
                });
            }

            if (results.length >= 10) break;
        }

        return NextResponse.json(results, { status: 200 });
    } catch (error: any) {
        return NextResponse.json({ error: error.message }, { status: 500 });
    }
}
