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

const VALID_PERIODS: LoyaltyStatsPeriod[] = ['today', 'week', 'month', '3months'];

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId, branchId } = req.session;
    await requireSection(req, 'loyalty');
    await requirePlanFeature(restaurantId!, 'loyalty');
    const url = new URL(req.url);
    const rawPeriod = url.searchParams.get('period') ?? 'month';
    const period: LoyaltyStatsPeriod = VALID_PERIODS.includes(rawPeriod as LoyaltyStatsPeriod)
      ? (rawPeriod as LoyaltyStatsPeriod)
      : 'month';
    const bId = url.searchParams.get('branch_id') ?? branchId ?? undefined;
    const stats = await getLoyaltyStats(restaurantId!, period, bId);
    return NextResponse.json(stats);
  })
);
