/**
 * SERP Features Dashboard API Route
 * GET /api/serp-features/dashboard - Get SERP feature tracking dashboard data
 */

import { NextRequest, NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';
import { AuthMiddleware } from '@/lib/auth';

const prisma = new PrismaClient();

export async function GET(request: NextRequest) {
  try {
    // Require admin role
    const authResult = await AuthMiddleware.requireRole(request, 'ADMIN');
    if (authResult instanceof NextResponse) {
      return authResult;
    }

    const { searchParams } = new URL(request.url);
    const siteId = searchParams.get('siteId');
    const days = parseInt(searchParams.get('days') || '30', 10);

    const startDate = new Date();
    startDate.setDate(startDate.getDate() - days);

    // Get all SERP features
    const features = await prisma.sERPFeature.findMany({
      where: siteId ? { siteId } : undefined,
      orderBy: { updatedAt: 'desc' },
    });

    // Calculate metrics
    const totalTracked = features.length;
    const captured = features.filter(f => f.captured);
    const uncaptured = features.filter(f => !f.captured);

    // Group by feature type
    const byType = {
      snippet: {
        total: features.filter(f => f.featureType === 'snippet').length,
        captured: features.filter(f => f.featureType === 'snippet' && f.captured).length,
      },
      paa: {
        total: features.filter(f => f.featureType === 'paa').length,
        captured: features.filter(f => f.featureType === 'paa' && f.captured).length,
      },
      ai_overview: {
        total: features.filter(f => f.featureType === 'ai_overview').length,
        mentions: features.filter(f => f.featureType === 'ai_overview' && f.aiOverviewMention).length,
      },
      local_pack: {
        total: features.filter(f => f.featureType === 'local_pack').length,
        captured: features.filter(f => f.featureType === 'local_pack' && f.captured).length,
      },
    };

    // Recent captures (last N days)
    const recentCaptures = captured
      .filter(f => f.capturedAt && f.capturedAt >= startDate)
      .sort((a, b) => (b.capturedAt?.getTime() || 0) - (a.capturedAt?.getTime() || 0))
      .slice(0, 20)
      .map(f => ({
        id: f.id,
        keyword: f.keyword,
        featureType: f.featureType,
        capturedAt: f.capturedAt,
      }));

    // Top opportunities (uncaptured, high potential)
    const opportunities = uncaptured
      .slice(0, 20)
      .map(f => ({
        id: f.id,
        keyword: f.keyword,
        featureType: f.featureType,
        detectedAt: f.detectedAt,
        optimized: f.optimized,
      }));

    // Optimization status
    const optimizationStats = {
      total: features.length,
      optimized: features.filter(f => f.optimized).length,
      pending: features.filter(f => !f.optimized && !f.captured).length,
    };

    return NextResponse.json({
      summary: {
        totalTracked,
        totalCaptured: captured.length,
        captureRate: totalTracked > 0 ? (captured.length / totalTracked * 100).toFixed(1) : 0,
        aiOverviewMentions: byType.ai_overview.mentions,
      },
      byType,
      recentCaptures,
      opportunities,
      optimization: optimizationStats,
      period: {
        start: startDate.toISOString(),
        end: new Date().toISOString(),
        days,
      },
    });
  } catch (error) {
    console.error('[API] SERP features dashboard error:', error);
    return NextResponse.json(
      { error: 'Failed to fetch SERP features dashboard' },
      { status: 500 }
    );
  }
}
