import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { getLocale } from 'next-intl/server';

export async function GET() {
  try {
    const locale = await getLocale();
    
    const menus = await prisma.menu.findMany({
      where: { isActive: true },
      include: {
        parent: true,
      },
      orderBy: { createdAt: 'asc' },
    });

    const getLocalizedName = (json: any) => {
      if (!json) return '';
      return json[locale] || json['id'] || json['en'] || '';
    };

    const formattedMenus = menus.map((menu) => {
      const name = getLocalizedName(menu.name);
      const parentName = menu.parent ? getLocalizedName(menu.parent.name) : '';
      return {
        id: menu.id,
        title: parentName ? `${parentName} > ${name}` : name,
      };
    });

    // Sort by title for better UX
    formattedMenus.sort((a, b) => a.title.localeCompare(b.title));

    return NextResponse.json({ success: true, data: formattedMenus });
  } catch (error) {
    console.error('Error fetching menus:', error);
    return NextResponse.json(
      { success: false, message: 'Failed to fetch menus' },
      { status: 500 }
    );
  }
}