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

async function handler(req: AuthenticatedRequest) {
    try {
        const { name, description, image_url, show_on_homepage } = await req.json();

        if (!name || name.length < 2) {
            return NextResponse.json({ error: 'Name too short' }, { status: 400 });
        }

        const [result] = await pool.query<ResultSetHeader>(
            'INSERT INTO categories (name, description, image_url, show_on_homepage) VALUES (?, ?, ?, ?)',
            [name, description || null, image_url || null, show_on_homepage ? 1 : 0]
        );

        return NextResponse.json({
            success: true,
            category: { id: result.insertId, name, description, image_url, show_on_homepage }
        });

    } catch (error) {
        console.error('Create category error:', error);
        return NextResponse.json({ error: 'Failed to create category' }, { status: 500 });
    }
}

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

export const POST = requireAdmin(handler);
