import { NextRequest, NextResponse } from 'next/server';
import pool from '@/lib/db';
import { RowDataPacket } from 'mysql2';

export async function GET(req: NextRequest) {
    try {
        const { searchParams } = new URL(req.url);
        const q = searchParams.get('q');

        if (!q || q.length < 2) {
            return NextResponse.json([]);
        }

        const sql = `
            SELECT p.id, p.name, p.price, p.brand,
            (SELECT pi.image_url FROM product_images pi WHERE pi.product_id = p.id ORDER BY pi.is_primary DESC, pi.display_order ASC LIMIT 1) as image
            FROM products p
            LEFT JOIN product_categories pc ON p.id = pc.product_id
            LEFT JOIN categories c ON pc.category_id = c.id
            WHERE p.name LIKE ? OR p.brand LIKE ? OR c.name LIKE ?
            GROUP BY p.id
            LIMIT 5
        `;

        const searchTerm = `%${q}%`;
        const [rows] = await pool.query<RowDataPacket[]>(sql, [searchTerm, searchTerm, searchTerm]);

        return NextResponse.json(rows);
    } catch (error) {
        console.error('Autocomplete Error:', error);
        return NextResponse.json({ error: 'Failed to search' }, { status: 500 });
    }
}
