import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { logAuditEvent } from '@/lib/gfs/guardrails';
import { Prisma } from '@prisma/client';

export const dynamic = 'force-dynamic';

// GET — Fetch categories + menu items (for terminal + admin)
export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const includeInactive = searchParams.get('includeInactive') === 'true';

  const where = includeInactive ? {} : { isActive: true };

  const categories = await prisma.pOSCategory.findMany({
    where,
    orderBy: { sortOrder: 'asc' },
    include: {
      items: {
        where: includeInactive ? {} : { isActive: true },
        orderBy: { sortOrder: 'asc' },
      },
    },
  });

  return NextResponse.json({ categories });
}

// POST — Create or update category/item
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { type } = body; // 'category' | 'item'

    if (type === 'category') {
      const { id, name, displayName, color, icon, sortOrder, isActive } = body;
      if (id) {
        const cat = await prisma.pOSCategory.update({
          where: { id },
          data: { name, displayName, color, icon, sortOrder, isActive },
        });
        return NextResponse.json({ category: cat });
      }
      const cat = await prisma.pOSCategory.create({
        data: { name, displayName, color: color || '#3b82f6', icon, sortOrder: sortOrder || 0 },
      });
      return NextResponse.json({ category: cat }, { status: 201 });
    }

    if (type === 'item') {
      const { id, name, shortName, description, categoryId, price, costPrice, taxRate, sku, barcode, color, sortOrder, isActive, modifierGroups } = body;
      const data: Record<string, unknown> = {
        name, shortName, description, categoryId, price: Number(price), costPrice: Number(costPrice || 0),
        taxRate: Number(taxRate || 0), sku, barcode, color: color || '#3b82f6',
        sortOrder: sortOrder || 0, isActive: isActive !== false,
      };
      if (modifierGroups) data.modifierGroups = modifierGroups;

      if (id) {
        const item = await prisma.pOSMenuItem.update({ where: { id }, data: data as Prisma.POSMenuItemUpdateInput });
        return NextResponse.json({ item });
      }
      const createData = { ...data } as Record<string, unknown>;
      delete createData.categoryId;
      (createData as any).category = { connect: { id: categoryId } };
      const item = await prisma.pOSMenuItem.create({ data: createData as Prisma.POSMenuItemCreateInput });
      await logAuditEvent({
        action: 'create', resource: 'pos_menu_item', resourceId: item.id,
        performedBy: 'system', reason: 'Menu item created',
        previousState: {}, newState: { name: item.name, price: item.price },
      });
      return NextResponse.json({ item }, { status: 201 });
    }

    return NextResponse.json({ error: 'Invalid type' }, { status: 400 });
  } catch (error) {
    console.error('POS menu error:', error);
    return NextResponse.json({ error: 'Failed to save menu data' }, { status: 500 });
  }
}
