import { NextResponse } from 'next/server';
import { z } from 'zod';
import { withErrorHandler } 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 { listTiers, createTier } from '@server/services/loyalty.service';

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

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId } = req.session;
    await requireSection(req, 'loyalty');
    await requirePlanFeature(restaurantId!, 'loyalty');
    const tiers = await listTiers(restaurantId!);
    return NextResponse.json({ tiers });
  })
);

const createTierSchema = z.object({
  name: z.string().min(1).max(80),
  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 POST = withErrorHandler(
  withAuth(
    withValidationAuthed(createTierSchema, async (req) => {
      const { restaurantId, role } = req.session;
      if (!role || !CONFIG_ROLES.has(role)) {
        throw new ForbiddenError('Only owners or managers can create loyalty tiers');
      }
      await requireSection(req, 'loyalty', 'create');
      await requirePlanFeature(restaurantId!, 'loyalty');
      const tier = await createTier(restaurantId!, req.parsedBody);
      return NextResponse.json({ tier }, { status: 201 });
    })
  )
);
