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

// GET single category
async function getHandler(
    req: AuthenticatedRequest,
    { params }: { params: Promise<{ id: string }> }
) {
    try {
        const { id } = await params;
        const [categories] = await pool.query<RowDataPacket[]>(
            'SELECT * FROM categories WHERE id = ?',
            [id]
        );

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

        return NextResponse.json(categories[0]);
    } catch (error) {
        console.error('Get category error:', error);
        return NextResponse.json(
            { error: 'Internal server error' },
            { status: 500 }
        );
    }
}

// PUT update category
async function putHandler(
    req: AuthenticatedRequest,
    { params }: { params: Promise<{ id: string }> }
) {
    try {
        const { id } = await params;
        const body: UpdateCategoryRequest = await req.json();
        const { name, description } = body;

        // Check if category exists
        const [existing] = await pool.query<RowDataPacket[]>(
            'SELECT * FROM categories WHERE id = ?',
            [id]
        );

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

        // Build update query dynamically
        const updates: string[] = [];
        const values: (string | number | null)[] = [];

        if (name !== undefined) {
            updates.push('name = ?');
            values.push(name);
        }

        if (description !== undefined) {
            updates.push('description = ?');
            values.push(description);
        }

        if (body.image_url !== undefined) {
            updates.push('image_url = ?');
            values.push(body.image_url || null);
        }

        if (body.show_on_homepage !== undefined) {
            updates.push('show_on_homepage = ?');
            values.push(body.show_on_homepage ? 1 : 0);
        }

        if (updates.length === 0) {
            return NextResponse.json(
                { error: 'No fields to update' },
                { status: 400 }
            );
        }

        values.push(id);

        await pool.query(
            `UPDATE categories SET ${updates.join(', ')} WHERE id = ?`,
            values
        );

        // Fetch updated category
        const [updated] = await pool.query<RowDataPacket[]>(
            'SELECT * FROM categories WHERE id = ?',
            [id]
        );

        return NextResponse.json(updated[0]);
    } catch (error) {
        console.error('Update category error:', error);
        return NextResponse.json(
            { error: 'Internal server error' },
            { status: 500 }
        );
    }
}

// DELETE category
async function deleteHandler(
    req: AuthenticatedRequest,
    { params }: { params: Promise<{ id: string }> }
) {
    try {
        const { id } = await params;

        // Check if category has products
        const [products] = await pool.query<RowDataPacket[]>(
            'SELECT COUNT(*) as count FROM products WHERE category_id = ?',
            [id]
        );

        if (products[0].count > 0) {
            return NextResponse.json(
                { error: 'Cannot delete category with existing products' },
                { status: 409 }
            );
        }

        // Delete category
        const [result] = await pool.query<ResultSetHeader>(
            'DELETE FROM categories WHERE id = ?',
            [id]
        );

        if (result.affectedRows === 0) {
            return NextResponse.json(
                { error: 'Category not found' },
                { status: 404 }
            );
        }

        return NextResponse.json({ message: 'Category deleted successfully' });
    } catch (error) {
        console.error('Delete category error:', error);
        return NextResponse.json(
            { error: 'Internal server error' },
            { status: 500 }
        );
    }
}

export const GET = requireAdmin(getHandler);
export const PUT = requireAdmin(putHandler);
export const DELETE = requireAdmin(deleteHandler);
