import { NextRequest, NextResponse } from 'next/server';
import { getAuth } from 'firebase-admin/auth';
import { getFirebaseAdmin } from '@/lib/firebase-admin';
import { ADMIN_EMAILS } from '@/lib/constants';
import { getUsageSummary } from '@/lib/monitoring/costMonitor';
import { checkDailyCostAlert, detectAnomalousTraffic } from '@/lib/monitoring/alerting';

// ─────────────────────────────────────────────
// 어드민 인증 (기존 프로젝트 패턴)
// ─────────────────────────────────────────────

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/monitoring
// Query params: ?period=daily|weekly|monthly&date=YYYY-MM-DD
// ─────────────────────────────────────────────

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

        const { searchParams } = new URL(req.url);
        const periodParam = searchParams.get('period') ?? 'daily';
        const dateParam = searchParams.get('date') ?? undefined;

        const validPeriods = ['daily', 'weekly', 'monthly'] as const;
        type Period = (typeof validPeriods)[number];

        if (!validPeriods.includes(periodParam as Period)) {
            return NextResponse.json(
                { error: `Invalid period. Must be one of: ${validPeriods.join(', ')}` },
                { status: 400 }
            );
        }

        const period = periodParam as Period;

        // 기준 날짜 유효성 검사
        if (dateParam && !/^\d{4}-\d{2}-\d{2}$/.test(dateParam)) {
            return NextResponse.json(
                { error: 'Invalid date format. Use YYYY-MM-DD' },
                { status: 400 }
            );
        }

        const resolvedDate = dateParam ?? new Date().toISOString().split('T')[0];

        // 사용량 조회 + 경고 감지 병렬 실행
        const [summaryResult, costAlert, trafficAnomaly] = await Promise.all([
            getUsageSummary({ period, date: resolvedDate }),
            checkDailyCostAlert(resolvedDate),
            detectAnomalousTraffic(resolvedDate),
        ]);

        return NextResponse.json({
            period,
            date: resolvedDate,
            usage: summaryResult.data,
            totalCost: summaryResult.totalCost,
            avgDailyCost: summaryResult.avgDailyCost,
            alerts: {
                costAlert,
                trafficAnomaly,
            },
        });
    } catch (error: any) {
        console.error('Admin monitoring GET error:', error);
        return NextResponse.json(
            { error: 'Internal Server Error', message: error.message },
            { status: 500 }
        );
    }
}
