import { NextResponse } from 'next/server';
import { withV1ErrorHandler } from '@server/middleware/v1Errors';
import { withApiKey, ApiKeyRequest } from '@server/middleware/withApiKey';
import { withV1Validation } from '@server/middleware/v1Validation';
import { ParsedRequest } from '@server/middleware/withValidation';
import { parseListParams, buildListEnvelope, CursorError, cursorErrorResponse } from '@server/middleware/v1Pagination';
import { createMenuItemSchema, CreateMenuItemInput } from '@server/validators/menu.validator';
import { listItems, createItem } from '@server/services/menu.service';

export const GET = withV1ErrorHandler(
  withApiKey(async (req: ApiKeyRequest) => {
    const url = new URL(req.url);
    let pager;
    // Menu items default to a larger page size than other resources because
    // most callers want the whole catalogue at once for search/filtering.
    try { pager = parseListParams(url, 50, 200); }
    catch (e) { if (e instanceof CursorError) return cursorErrorResponse(e); throw e; }

    const result = await listItems({
      restaurantId: req.apiKey.restaurantId,
      branchId: url.searchParams.get('branch_id') ?? undefined,
      categoryId: url.searchParams.get('category_id') ?? undefined,
      search: url.searchParams.get('search') ?? undefined,
      page: pager.page,
      limit: pager.limit,
    });
    return NextResponse.json(buildListEnvelope(result.data, pager.page, pager.limit));
  }, { permission: 'menu:read' })
);

export const POST = withV1ErrorHandler(
  withApiKey(
    withV1Validation(createMenuItemSchema, async (req: ParsedRequest<CreateMenuItemInput>) => {
      const apiReq = req as ParsedRequest<CreateMenuItemInput> & ApiKeyRequest;
      const item = await createItem(
        apiReq.apiKey.restaurantId,
        req.parsedBody as unknown as Record<string, unknown>
      );
      return NextResponse.json({ data: item }, { status: 201 });
    }),
    { permission: 'menu:write' }
  )
);
