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);

        // Pagination
        const page = Math.max(1, parseInt(searchParams.get('page') || '1'));
        const limit = Math.max(1, Math.min(50, parseInt(searchParams.get('limit') || '12')));
        const offset = (page - 1) * limit;

        // Filters
        const q = searchParams.get('q');
        const sort = searchParams.get('sort') || 'newest';
        const minPrice = searchParams.get('minPrice');
        const maxPrice = searchParams.get('maxPrice');
        const brands = searchParams.get('brands'); // comma separated
        const conditions = searchParams.get('conditions'); // comma separated
        const materials = searchParams.get('materials'); // comma separated
        const colors = searchParams.get('colors'); // comma separated
        const categoryId = searchParams.get('category_id');
        const inStock = searchParams.get('in_stock');

        // Build Query - primary_image comes from product_images table first
        let sql = `
            SELECT SQL_CALC_FOUND_ROWS p.*, 
            (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 primary_image,
            GROUP_CONCAT(DISTINCT c.name) as category_names
            FROM products p
            LEFT JOIN product_categories pc ON p.id = pc.product_id
            LEFT JOIN categories c ON pc.category_id = c.id
        `;

        const whereConditions: string[] = [];
        const params: (string | number)[] = [];

        // Search (Name or Description or Brand or Category Name)
        if (q) {
            whereConditions.push(`(
                p.name LIKE ? OR 
                p.description LIKE ? OR 
                p.brand LIKE ? OR
                c.name LIKE ?
            )`);
            const searchTerm = `%${q}%`;
            params.push(searchTerm, searchTerm, searchTerm, searchTerm);
        }

        // Price Range
        if (minPrice) {
            whereConditions.push('p.price >= ?');
            params.push(minPrice);
        }
        if (maxPrice) {
            whereConditions.push('p.price <= ?');
            params.push(maxPrice);
        }

        // Brands
        if (brands) {
            const brandList = brands.split(',');
            whereConditions.push(`p.brand IN (${brandList.map(() => '?').join(',')})`);
            params.push(...brandList);
        }

        // Conditions
        if (conditions) {
            const conditionList = conditions.split(',');
            whereConditions.push(`p.product_condition IN (${conditionList.map(() => '?').join(',')})`);
            params.push(...conditionList);
        }

        // Materials
        if (materials) {
            const materialList = materials.split(',');
            whereConditions.push(`p.material IN (${materialList.map(() => '?').join(',')})`);
            params.push(...materialList);
        }

        // Colors
        if (colors) {
            const colorList = colors.split(',');
            whereConditions.push(`p.color IN (${colorList.map(() => '?').join(',')})`);
            params.push(...colorList);
        }

        // Category (Include subcategories 1 level deep)
        if (categoryId) {
            // This is simplified. For full recursion, we'd need more logic.
            // Check if product belongs to this category OR any of its children
            whereConditions.push(`p.id IN (
                SELECT pc2.product_id 
                FROM product_categories pc2
                JOIN categories c2 ON pc2.category_id = c2.id
                WHERE c2.id = ? OR c2.parent_id = ?
            )`);
            params.push(categoryId, categoryId);
        }

        // Stock Status
        if (inStock === 'true') {
            whereConditions.push("p.stock_status = 'in_stock'");
        }

        if (whereConditions.length > 0) {
            sql += ' WHERE ' + whereConditions.join(' AND ');
        }

        // Group By
        sql += ' GROUP BY p.id';

        // Sorting
        switch (sort) {
            case 'price_asc':
                sql += ' ORDER BY p.price ASC';
                break;
            case 'price_desc':
                sql += ' ORDER BY p.price DESC';
                break;
            case 'name_asc':
                sql += ' ORDER BY p.name ASC';
                break;
            case 'name_desc':
                sql += ' ORDER BY p.name DESC';
                break;
            case 'newest':
                sql += ' ORDER BY p.created_at DESC';
                break;
            case 'random':
                sql += ' ORDER BY RAND()';
                break;
            default:
                sql += ' ORDER BY p.created_at DESC';
                break;
        }

        // Pagination
        sql += ' LIMIT ? OFFSET ?';
        params.push(limit, offset);

        const [rows] = await pool.query<RowDataPacket[]>(sql, params);

        // Get total count
        const [countResult] = await pool.query<RowDataPacket[]>('SELECT FOUND_ROWS() as total');
        const total = countResult[0].total;

        return NextResponse.json({
            products: rows,
            pagination: {
                total,
                page,
                limit,
                totalPages: Math.ceil(total / limit)
            }
        });

    } catch (error) {
        console.error('Search API Error:', error);
        return NextResponse.json({ error: 'Failed to fetch products' }, { status: 500 });
    }
}
