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

interface Params {
    params: Promise<{ id: string }>;
}

export async function GET(req: NextRequest, { params }: Params) {
    try {
        const { id } = await params;
        const productId = parseInt(id);

        if (isNaN(productId)) {
            return NextResponse.json({ error: 'Invalid product ID' }, { status: 400 });
        }

        // Fetch product with joined data
        const [rows] = await pool.query<RowDataPacket[]>(`
            SELECT p.*, 
            GROUP_CONCAT(DISTINCT pi.image_url ORDER BY pi.is_primary DESC, pi.display_order ASC) as product_images,
            GROUP_CONCAT(DISTINCT c.name) as category_names
            FROM products p
            LEFT JOIN product_images pi ON p.id = pi.product_id
            LEFT JOIN product_categories pc ON p.id = pc.product_id
            LEFT JOIN categories c ON pc.category_id = c.id
            WHERE p.id = ?
            GROUP BY p.id
        `, [productId]);

        if (rows.length === 0) {
            return NextResponse.json({ error: 'Product not found' }, { status: 404 });
        }

        const product = rows[0];

        // Format images - product_images table is the source of truth for uploaded images
        const uploadedImages = product.product_images ? product.product_images.split(',') : [];
        const allImages = uploadedImages;

        const formattedProduct = {
            ...product,
            images: allImages,
            category_names: product.category_names ? product.category_names.split(',') : [],
            price: Number(product.price),
            original_price: product.original_price ? Number(product.original_price) : null
        };

        return NextResponse.json(formattedProduct);

    } catch (error) {
        console.error('Fetch product detail error:', error);
        return NextResponse.json({ error: 'Failed to fetch product' }, { status: 500 });
    }
}
