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

export async function GET() {
    try {
        const [categories] = await pool.query<RowDataPacket[]>('SELECT * FROM categories ORDER BY name ASC');

        const [brands] = await pool.query<RowDataPacket[]>(`
            SELECT brand, COUNT(*) as count 
            FROM products 
            WHERE brand IS NOT NULL AND brand != ''
            GROUP BY brand 
            ORDER BY count DESC
        `);

        const [materials] = await pool.query<RowDataPacket[]>(`
            SELECT material, COUNT(*) as count 
            FROM products 
            WHERE material IS NOT NULL AND material != ''
            GROUP BY material 
            ORDER BY count DESC
        `);

        const [conditions] = await pool.query<RowDataPacket[]>(`
            SELECT product_condition, COUNT(*) as count 
            FROM products 
            GROUP BY product_condition 
            ORDER BY count DESC
        `);

        const [colors] = await pool.query<RowDataPacket[]>(`
            SELECT color, COUNT(*) as count 
            FROM products 
            WHERE color IS NOT NULL AND color != ''
            GROUP BY color 
            ORDER BY count DESC
        `);

        const [priceRange] = await pool.query<RowDataPacket[]>(`
            SELECT MIN(price) as min, MAX(price) as max FROM products
        `);

        // Build Category Tree
        // Build Category Tree
        interface CategoryNode extends RowDataPacket {
            id: number;
            parent_id: number | null;
            name: string;
            children: CategoryNode[];
        }

        const categoryMap = new Map<number, CategoryNode>();
        const categoryTree: CategoryNode[] = [];

        // 1. Initialize map
        categories.forEach((cat) => {
            // Need cast because RowDataPacket doesn't strictly adhere to our interface without it
            const node = { ...cat, children: [] } as CategoryNode;
            categoryMap.set(node.id, node);
        });

        // 2. Build tree
        categoryMap.forEach((node) => {
            if (node.parent_id && categoryMap.has(node.parent_id)) {
                categoryMap.get(node.parent_id)?.children.push(node);
            } else {
                categoryTree.push(node);
            }
        });

        return NextResponse.json({
            categories: categoryTree,
            brands,
            materials,
            conditions,
            colors,
            priceRange: priceRange[0]
        });

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