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, refundCard } 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', 'update');
    await requirePlanFeature(restaurantId, 'gift_cards');
    if (!['owner', 'admin'].includes(req.session.role || '')) {
      throw new ForbiddenError('Only owners and admins can refund 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(() => null);
    if (!body || typeof body.amount !== 'number') throw new ValidationError('amount is required');
    const result = await refundCard(restaurantId, id, body.amount, req.session.userId ?? null, body.note ?? null);
    return NextResponse.json(result);
  })
);
