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

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

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 rawPeriod = p.get('period') ?? 'week';
    const period: AnalyticsPeriod = VALID_PERIODS.includes(rawPeriod as AnalyticsPeriod)
      ? (rawPeriod as AnalyticsPeriod)
      : 'week';
    const bId = p.get('branch_id') ?? branchId ?? undefined;
    const data = await getFullAnalytics(restaurantId!, period, bId);
    return NextResponse.json(data);
  })
);
