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

const CONFIG_ROLES = new Set(['owner', 'manager', 'superadmin', 'support']);

const updateTierSchema = z.object({
  name: z.string().min(1).max(80).optional(),
  threshold: z.number().min(0).optional(),
  earn_multiplier: z.number().min(0).optional(),
  auto_discount_pct: z.number().min(0).max(100).optional(),
  free_delivery: z.boolean().optional(),
  perks_text: z.string().max(500).nullable().optional(),
  badge_color: z.string().max(20).nullable().optional(),
  display_order: z.number().int().optional(),
});

export const PATCH = withErrorHandler(
  withAuth(
    withValidationAuthed(updateTierSchema, async (req, ctx: RouteContext) => {
      const { restaurantId, role } = req.session;
      if (!role || !CONFIG_ROLES.has(role)) {
        throw new ForbiddenError('Only owners or managers can edit loyalty tiers');
      }
      await requireSection(req, 'loyalty', 'update');
      await requirePlanFeature(restaurantId!, 'loyalty');
      const { id } = await ctx.params;
      const tier = await updateTier(restaurantId!, id, req.parsedBody);
      return NextResponse.json({ tier });
    })
  )
);

export const DELETE = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    const { restaurantId, role } = req.session;
    if (!role || !CONFIG_ROLES.has(role)) {
      throw new ForbiddenError('Only owners or managers can delete loyalty tiers');
    }
    await requireSection(req, 'loyalty', 'delete');
    await requirePlanFeature(restaurantId!, 'loyalty');
    const { id } = await ctx.params;
    await deleteTier(restaurantId!, id);
    return NextResponse.json({ success: true });
  })
);
