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

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    const { id } = await ctx.params;
    const restaurantId = req.session.restaurantId!;
    await requireSection(req, 'gift_cards');
    await requirePlanFeature(restaurantId, 'gift_cards');
    // Vouchers contain the masked code, recipient details, and branding —
    // a pinned-staff user must not be able to PDF a sibling branch's card.
    const card = await getCard(restaurantId, id);
    assertBranchAccess(req.session, card.issued_branch_id, { allowNull: true });
    const { pdf, filename } = await buildVoucherForCard(restaurantId, id);
    return new Response(new Uint8Array(pdf), {
      status: 200,
      headers: {
        'Content-Type': 'application/pdf',
        'Content-Disposition': `inline; filename="${filename}"`,
        'Cache-Control': 'private, no-cache',
      },
    });
  })
);
