import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import { requirePlanFeature } from '@server/utils/features';
import { listLedger } from '@server/services/loyalty.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    const { restaurantId } = req.session;
    await requireSection(req, 'loyalty');
    await requirePlanFeature(restaurantId!, 'loyalty');
    const { id } = await ctx.params;
    const url = new URL(req.url);
    const page = Math.max(1, parseInt(url.searchParams.get('page') ?? '1', 10));
    const limit = Math.min(100, Math.max(1, parseInt(url.searchParams.get('limit') ?? '50', 10)));
    const result = await listLedger(restaurantId!, id, page, limit);
    return NextResponse.json(result);
  })
);
