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

async function verifyAdmin(req: NextRequest): Promise<{ email: string } | NextResponse> {
    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 });
    }
    return { email: userEmail };
}

// GET /api/admin/insurance/terms/[productId]
export async function GET(
    req: NextRequest,
    { params }: { params: Promise<{ productId: string }> }
) {
    try {
        const authResult = await verifyAdmin(req);
        if (authResult instanceof NextResponse) return authResult;

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

        const db = getFirebaseAdmin().firestore();

        // insurance_metadata 조회 (id = companyId_productId 형식)
        // productId 기준으로 조회
        const snapshot = await db
            .collection('insurance_metadata')
            .where('productId', '==', productId)
            .limit(1)
            .get();

        if (snapshot.empty) {
            // id로도 시도
            const docRef = await db.collection('insurance_metadata').doc(productId).get();
            if (!docRef.exists) {
                return NextResponse.json({ error: 'Product not found' }, { status: 404 });
            }
            const data = docRef.data()!;
            return NextResponse.json({
                metadata: {
                    id: docRef.id,
                    ...data,
                    createdAt: data.createdAt?.toDate?.()?.toISOString() ?? null,
                    updatedAt: data.updatedAt?.toDate?.()?.toISOString() ?? null,
                },
            });
        }

        const doc = snapshot.docs[0];
        const data = doc.data();

        return NextResponse.json({
            metadata: {
                id: doc.id,
                ...data,
                createdAt: data.createdAt?.toDate?.()?.toISOString() ?? null,
                updatedAt: data.updatedAt?.toDate?.()?.toISOString() ?? null,
            },
        });
    } catch (error: any) {
        console.error('GET /api/admin/insurance/terms/[productId] error:', error);
        return NextResponse.json({ error: 'Internal Server Error', message: error.message }, { status: 500 });
    }
}
