import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import { ForbiddenError } from '@server/errors';
import { getSettings, updateSettings } from '@server/services/gift-cards.service';
import { requirePlanFeature } from '@server/utils/features';

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

export const PUT = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    await requireSection(req, 'gift_cards', 'update');
    await requirePlanFeature(req.session.restaurantId!, 'gift_cards');
    if (!['owner', 'admin'].includes(req.session.role || '')) {
      throw new ForbiddenError('Only owners and admins can change gift card settings');
    }
    const body = await req.json();
    const settings = await updateSettings(req.session.restaurantId!, body);
    return NextResponse.json({ settings });
  })
);
