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

async function updateHandler(req: AuthenticatedRequest, context: { params: Promise<{ id: string }> }) {
    const { id } = await context.params;
    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. Update Product
        await connection.query(`
            UPDATE products SET 
                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 = ?
            WHERE id = ?
        `, [
            category_ids?.[0] || 1,
            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,
            id
        ]);

        // 2. Update Images (Strategy: Delete all and re-insert)
        // A better strategy would be to diff, but this is simpler for MVP
        if (images) {
            await connection.query('DELETE FROM product_images WHERE product_id = ?', [id]);

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

        // 3. Update Categories (Strategy: Delete all and re-insert)
        if (category_ids) {
            await connection.query('DELETE FROM product_categories WHERE product_id = ?', [id]);

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

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

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

async function deleteHandler(req: AuthenticatedRequest, context: { params: Promise<{ id: string }> }) {
    const { id } = await context.params;

    try {
        await pool.query('DELETE FROM products WHERE id = ?', [id]);
        return NextResponse.json({ success: true, message: 'Produkten har raderats' });
    } catch (error) {
        console.error('Delete product error:', error);
        return NextResponse.json({ error: 'Failed to delete product' }, { status: 500 });
    }
}

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

export const PUT = requireAdmin(updateHandler);
export const DELETE = requireAdmin(deleteHandler);
