// /api/discover/niche-history — Feature 1: Return score trend for a niche name
import { NextRequest, NextResponse } from 'next/server';
import pool from '../../../../lib/db';
import '../../../../lib/discoverDb';

export async function GET(req: NextRequest) {
    const { searchParams } = new URL(req.url);
    const name = searchParams.get('name');
    if (!name) return NextResponse.json({ error: 'name required' }, { status: 400 });

    try {
        // Return up to 20 most recent score snapshots for this niche
        const [rows] = await pool.execute<any[]>(
            `SELECT score, session_count, item_count, crawled_at
             FROM niche_score_history
             WHERE niche_name = ?
             ORDER BY crawled_at ASC
             LIMIT 20`,
            [name]
        );
        return NextResponse.json({ name, history: rows });
    } catch (err: any) {
        return NextResponse.json({ error: err.message }, { status: 500 });
    }
}
