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

export async function GET() {
  try {
    const menus = await db.menu.findMany({
      orderBy: { order: 'asc' },
      include: {
        subItems: {
          orderBy: { order: 'asc' },
        },
      },
    });
    return NextResponse.json({ success: true, menus });
  } catch (error) {
    console.error('Fetch menus error:', error);
    return NextResponse.json({ success: false, error: 'Failed to fetch menus' }, { status: 500 });
  }
}

export async function POST(req: NextRequest) {
  try {
    const { title, slug, icon, path, order, parentId, isVisible } = await req.json();

    if (!title || !slug) {
      return NextResponse.json({ success: false, error: 'Title and slug are required' }, { status: 400 });
    }

    await db.menu.create({
      data: {
        title,
        slug,
        icon: icon || null,
        path: path || null,
        order: order || 0,
        parentId: parentId || null,
        isVisible: isVisible !== false,
      },
    });

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

export async function PATCH(req: NextRequest) {
  try {
    const { id, ...data } = await req.json();

    if (!id) {
      return NextResponse.json({ success: false, error: 'ID is required' }, { status: 400 });
    }

    const updateData: Record<string, unknown> = {};
    if (data.title !== undefined) updateData.title = data.title;
    if (data.slug !== undefined) updateData.slug = data.slug;
    if (data.icon !== undefined) updateData.icon = data.icon;
    if (data.path !== undefined) updateData.path = data.path;
    if (data.order !== undefined) updateData.order = data.order;
    if (data.parentId !== undefined) updateData.parentId = data.parentId || null;
    if (data.isVisible !== undefined) updateData.isVisible = data.isVisible;

    await db.menu.update({ where: { id }, data: updateData });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Update menu error:', error);
    return NextResponse.json({ success: false, error: 'Failed to update menu' }, { status: 500 });
  }
}

export async function DELETE(req: NextRequest) {
  try {
    const { id } = await req.json();

    if (!id) {
      return NextResponse.json({ success: false, error: 'ID is required' }, { status: 400 });
    }

    // Delete sub-items first
    await db.menu.deleteMany({ where: { parentId: id } });
    await db.menu.delete({ where: { id } });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Delete menu error:', error);
    return NextResponse.json({ success: false, error: 'Failed to delete menu' }, { status: 500 });
  }
}
