import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { getOrderTrends } from '@server/services/analytics.service';
import { requirePlanFeature } from '@server/utils/features';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId, branchId } = req.session;
    await requirePlanFeature(restaurantId!, 'analytics');
    const url = new URL(req.url);
    const p = url.searchParams;
    const days = parseInt(p.get('days') ?? '30', 10);
    const bId = p.get('branch_id') ?? branchId ?? undefined;
    const trends = await getOrderTrends(restaurantId!, days, bId);
    return NextResponse.json({ trends });
  })
);
