import { NextResponse } from 'next/server';
import { z } from 'zod';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { ForbiddenError } from '@server/errors';
import { withAuth, requireSection } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { requirePlanFeature } from '@server/utils/features';
import { adjustPoints } from '@server/services/loyalty.service';

const adjustSchema = z.object({
  delta: z.number().int().refine((n) => n !== 0, 'Delta must be a non-zero integer'),
  reason: z.string().min(1).max(500),
});

// Roles allowed to manually move loyalty points. Staff cannot adjust balances.
const ADJUST_ROLES = new Set(['owner', 'manager', 'superadmin', 'support']);

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(adjustSchema, async (req, ctx: RouteContext) => {
      const { restaurantId, userId, role } = req.session;
      if (!role || !ADJUST_ROLES.has(role)) {
        throw new ForbiddenError('Only owners or managers can adjust loyalty points');
      }
      await requireSection(req, 'loyalty', 'update');
      await requirePlanFeature(restaurantId!, 'loyalty');
      const { id } = await ctx.params;
      const result = await adjustPoints(restaurantId!, id, req.parsedBody.delta, req.parsedBody.reason, userId ?? null);
      return NextResponse.json(result);
    })
  )
);
