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

// GET: List all products with images and categories
async function getHandler(req: AuthenticatedRequest) {
    try {
        // Fetch products
        const [products] = await pool.query<RowDataPacket[]>(`
            SELECT p.*, 
            GROUP_CONCAT(DISTINCT pi.image_url ORDER BY pi.display_order ASC) as images,
            GROUP_CONCAT(DISTINCT c.id) as category_ids,
            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
            GROUP BY p.id
            ORDER BY p.created_at DESC
        `);

        // Format the output
        const formattedProducts = products.map(p => ({
            ...p,
            images: p.images ? p.images.split(',') : [],
            category_ids: p.category_ids ? p.category_ids.split(',').map(Number) : [],
            category_names: p.category_names ? p.category_names.split(',') : [],
            in_stock: p.stock_status === 'in_stock',
            price: Number(p.price),
            original_price: p.original_price ? Number(p.original_price) : null
        }));

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

// POST: Create a new product
async function postHandler(req: AuthenticatedRequest) {
    const connection = await pool.getConnection();
    await connection.beginTransaction();

    try {
        const body = await req.json();
        const {
            name, description, price, original_price,
            stock_status, stock,
            width, height, depth,
            brand, product_condition, material, color,
            category_ids, images,
            badge_text, badge_color, show_on_homepage
        } = body;

        // 1. Insert Product
        const [result] = await connection.query<ResultSetHeader>(`
            INSERT INTO products (
                category_id, name, description, price, original_price, 
                stock_status, stock, width, height, depth, 
                brand, product_condition, material, color,
                badge_text, badge_color, show_on_homepage
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        `, [
            category_ids?.[0] || 1, // Fallback to category 1 if none provided
            name, description, price, original_price || null,
            stock_status ? 'in_stock' : 'out_of_stock', stock || 0,
            width || null, height || null, depth || null,
            brand || null, product_condition, material || null, color || null,
            badge_text || null, badge_color || null, show_on_homepage ? 1 : 0
        ]);

        const productId = result.insertId;

        // 2. Insert Images
        if (images && images.length > 0) {
            const imageValues = images.map((url: string, index: number) =>
                [productId, url, index, index === 0]
            );
            await connection.query(
                `INSERT INTO product_images (product_id, image_url, display_order, is_primary) VALUES ?`,
                [imageValues]
            );
        }

        // 3. Insert Categories
        if (category_ids && category_ids.length > 0) {
            const categoryValues = category_ids.map((catId: number) =>
                [productId, catId]
            );
            await connection.query(
                `INSERT INTO product_categories (product_id, category_id) VALUES ?`,
                [categoryValues]
            );
        }

        await connection.commit();
        return NextResponse.json({ success: true, productId, message: 'Produkten har skapats' });

    } catch (error) {
        await connection.rollback();
        console.error('Create product error:', error);
        return NextResponse.json({ error: 'Failed to create product' }, { status: 500 });
    } finally {
        connection.release();
    }
}

import { requireAdmin } from '@/lib/middleware';

export const GET = requireAdmin(getHandler);
export const POST = requireAdmin(postHandler);
