// /api/discover/anomalies — Channel Velocity Anomaly Detection
// Pure DB math — no search.list needed. Uses channel_stats tracking history.

import { NextResponse } from 'next/server';
import pool from '../../../../lib/db';
import '../../../../lib/discoverDb';

export async function GET() {
    try {
        // Find anomalies in tracked channels (existing channel_stats table)
        const [anomalyRows] = await pool.execute<any[]>(`
            SELECT
                c.id, c.title, c.thumbnailUrl,
                s_now.subscriberCount AS subs,
                s_now.viewCount AS views_now,
                s_48.viewCount AS views_48h,
                s_7d.viewCount AS views_7d,
                ROUND(
                    (s_now.viewCount - s_48.viewCount) /
                    NULLIF((s_7d.viewCount / 7), 0) * 100, 1
                ) AS velocity_pct
            FROM channels c
            JOIN channel_stats s_now ON c.id = s_now.channel_id
                AND s_now.date = (SELECT MAX(date) FROM channel_stats WHERE channel_id = c.id)
            LEFT JOIN channel_stats s_48 ON c.id = s_48.channel_id
                AND s_48.date = DATE_SUB(CURDATE(), INTERVAL 2 DAY)
            LEFT JOIN channel_stats s_7d ON c.id = s_7d.channel_id
                AND s_7d.date = DATE_SUB(CURDATE(), INTERVAL 7 DAY)
            WHERE s_48.viewCount IS NOT NULL
              AND s_7d.viewCount IS NOT NULL
              AND s_now.viewCount > s_48.viewCount
            HAVING velocity_pct > 150
            ORDER BY velocity_pct DESC
            LIMIT 20
        `);

        return NextResponse.json({
            tracked: anomalyRows,
            fresh: [],   // Fresh API sweep removed — uses search.list (100 quota units each)
        });

    } catch (err: any) {
        console.error('[Anomalies]', err);
        return NextResponse.json({ error: err.message }, { status: 500 });
    }
}
