import { NextResponse } from 'next/server';
import { withWidgetCors, widgetOptionsResponse } from '../_cors';
import { db, menuCategories, menuItems } from '@server/db/drizzle';
import { eq, and, asc } from 'drizzle-orm';
import { initDatabase } from '@server/db/init';

export async function OPTIONS() { return widgetOptionsResponse(); }

const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

export const GET = withWidgetCors(async (req: Request) => {
  const url = new URL(req.url);
  const restaurantId = url.searchParams.get('restaurantId') || '';

  if (!UUID_RE.test(restaurantId)) {
    return NextResponse.json({ error: 'Invalid restaurantId' }, { status: 400 });
  }

  await initDatabase();

  const catRows = await db.select({
    id: menuCategories.id,
    name: menuCategories.name,
    display_order: menuCategories.displayOrder,
  })
  .from(menuCategories)
  .where(and(eq(menuCategories.restaurantId, restaurantId), eq(menuCategories.isActive, true)))
  .orderBy(asc(menuCategories.displayOrder), asc(menuCategories.name));

  const itemRows = await db.select({
    id: menuItems.id,
    category_id: menuItems.categoryId,
    name: menuItems.name,
    description: menuItems.description,
    price: menuItems.price,
    image_url: menuItems.imageUrl,
    is_available: menuItems.isAvailable,
    is_veg: menuItems.isVeg,
    dietary_tags: menuItems.dietaryTags,
  })
  .from(menuItems)
  .where(and(eq(menuItems.restaurantId, restaurantId), eq(menuItems.isAvailable, true)))
  .orderBy(asc(menuItems.sortOrder), asc(menuItems.name));

  const categories = catRows.map(cat => ({
    id: cat.id,
    name: cat.name,
    items: itemRows
      .filter(item => item.category_id === cat.id)
      .map(item => ({
        id: item.id,
        name: item.name,
        description: item.description || '',
        price: Number(item.price),
        image_url: item.image_url || null,
        is_available: item.is_available,
        is_veg: item.is_veg,
        category_name: cat.name,
      })),
  })).filter(cat => cat.items.length > 0);

  const uncategorized = itemRows
    .filter(item => !item.category_id)
    .map(item => ({
      id: item.id,
      name: item.name,
      description: item.description || '',
      price: Number(item.price),
      image_url: item.image_url || null,
      is_available: item.is_available,
      is_veg: item.is_veg,
      category_name: 'Other',
    }));

  if (uncategorized.length > 0) {
    categories.push({ id: '__other__', name: 'Other', items: uncategorized });
  }

  return NextResponse.json({ categories });
});
