import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import { ForbiddenError } from '@server/errors';
import { getCard, voidCard } from '@server/services/gift-cards.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', 'delete');
    await requirePlanFeature(restaurantId, 'gift_cards');
    if (!['owner', 'admin'].includes(req.session.role || '')) {
      throw new ForbiddenError('Only owners and admins can void gift cards');
    }
    const { id } = await ctx.params;
    const card = await getCard(restaurantId, id);
    assertBranchAccess(req.session, card.issued_branch_id, { allowNull: true });
    const body = await req.json().catch(() => ({}));
    const result = await voidCard(restaurantId, id, body?.reason ?? null, req.session.userId ?? null);
    return NextResponse.json(result);
  })
);
