import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import { getCard, getCardLedger } 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');
    const card = await getCard(restaurantId, id);
    assertBranchAccess(req.session, card.issued_branch_id, { allowNull: true });
    const ledger = await getCardLedger(restaurantId, id);
    return NextResponse.json({ card, ledger });
  })
);
