import type {NextRequest} from 'next/server';
import type {Granularity} from '@/features/dashboard/types/dashboard';
import {ok, parseQuery, requireApiSession, simulate, wantsEmpty} from '@/shared/services/apiRoute';
import {buildPeriodPerformance} from '@/features/dashboard/mock/analytics.mock';

export const dynamic = 'force-dynamic';

export async function GET(req: NextRequest) {
  const denied = await requireApiSession();
  if (denied) return denied;
  const q = parseQuery(req);
  const simulated = await simulate(q);
  if (simulated) return simulated;

  const raw = req.nextUrl.searchParams.get('granularity');
  const granularity: Granularity = raw === 'monthly' ? 'monthly' : 'weekly';

  return ok(
    wantsEmpty(q) ? [] : buildPeriodPerformance(granularity, q.storeId, q.nowMs),
    q,
  );
}
