// /api/niches/saved — Feature 12: Bookmark niches from the search page
import { NextRequest, NextResponse } from 'next/server';
import pool from '../../../../lib/db';
import '../../../../lib/discoverDb';

// GET — list all saved niches
export async function GET() {
    try {
        const [rows] = await pool.execute<any[]>(
            `SELECT * FROM saved_niches ORDER BY saved_at DESC`
        );
        return NextResponse.json({ niches: rows });
    } catch (err: any) {
        return NextResponse.json({ error: err.message }, { status: 500 });
    }
}

// POST — save / upsert a niche
export async function POST(req: NextRequest) {
    try {
        const { keyword, white_space_score = 0, label = '', notes = '' } = await req.json();
        if (!keyword?.trim()) return NextResponse.json({ error: 'keyword required' }, { status: 400 });

        await pool.execute(
            `INSERT INTO saved_niches (keyword, white_space_score, label, notes)
             VALUES (?, ?, ?, ?)
             ON DUPLICATE KEY UPDATE
               white_space_score = VALUES(white_space_score),
               label = VALUES(label),
               last_checked = CURRENT_TIMESTAMP`,
            [keyword.trim(), white_space_score, label, notes]
        );
        return NextResponse.json({ saved: true });
    } catch (err: any) {
        return NextResponse.json({ error: err.message }, { status: 500 });
    }
}

// DELETE — remove a saved niche
export async function DELETE(req: NextRequest) {
    try {
        const { searchParams } = new URL(req.url);
        const keyword = searchParams.get('keyword');
        if (!keyword) return NextResponse.json({ error: 'keyword required' }, { status: 400 });
        await pool.execute(`DELETE FROM saved_niches WHERE keyword = ?`, [keyword]);
        return NextResponse.json({ deleted: true });
    } catch (err: any) {
        return NextResponse.json({ error: err.message }, { status: 500 });
    }
}
