// /api/discover/crawl — Feature 1: YouTube Algo Feed
// POST: manual trigger | GET: cached results with score history for sparklines

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

async function getResultsWithHistory() {
    const [rows] = await pool.execute<any[]>(
        `SELECT * FROM discovered_niches WHERE source = 'algo_feed' ORDER BY score DESC LIMIT 50`
    );
    // Fetch last 10 score snapshots for each niche (for sparklines)
    const enriched = await Promise.all(rows.map(async (row: any) => {
        try {
            const [hist] = await pool.execute<any[]>(
                `SELECT score, crawled_at FROM niche_score_history
                 WHERE niche_name = ? ORDER BY crawled_at ASC LIMIT 10`,
                [row.name]
            );
            return { ...row, history: (hist as any[]).map((h: any) => h.score) };
        } catch {
            return { ...row, history: [] };
        }
    }));
    return enriched;
}

// GET — return cached results with sparkline history
export async function GET() {
    try {
        const results = await getResultsWithHistory();
        const [timeRows] = await pool.execute<any[]>(
            `SELECT MAX(crawled_at) AS last FROM algo_feed_snapshots`
        );
        return NextResponse.json({ results, lastCrawled: timeRows[0]?.last || null });
    } catch (err: any) {
        return NextResponse.json({ error: err.message }, { status: 500 });
    }
}

// POST — manual trigger
export async function POST() {
    try {
        const result = await runCrawlJob();
        const results = await getResultsWithHistory();
        return NextResponse.json({ ...result, results });
    } catch (err: any) {
        console.error('[Crawl POST]', err);
        return NextResponse.json({ error: err.message }, { status: 500 });
    }
}
