import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import { ForbiddenError, ValidationError } from '@server/errors';
import { getCard } from '@server/services/gift-cards.service';
import { enqueueGiftCardReminderEmail } from '@server/services/gift-cards-email.service';
import { assertBranchAccess } from '@server/utils/branch-access';
import { requirePlanFeature } from '@server/utils/features';

export const POST = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    const restaurantId = req.session.restaurantId!;
    await requireSection(req, 'gift_cards');
    await requirePlanFeature(restaurantId, 'gift_cards');
    if (!['owner', 'admin', 'manager'].includes(req.session.role || '')) {
      throw new ForbiddenError('You do not have permission to resend gift card emails');
    }
    const { id } = await ctx.params;
    const card = await getCard(restaurantId, id);
    assertBranchAccess(req.session, card.issued_branch_id, { allowNull: true });
    if (!card.recipient_email) throw new ValidationError('Card has no recipient email on file');
    await enqueueGiftCardReminderEmail({ restaurantId, cardId: id });
    return NextResponse.json({ ok: true });
  })
);
