import type {NextRequest} from 'next/server';
import type {Granularity} from '@/lib/api/contracts';
import {ok, parseQuery, simulate, wantsEmpty} from '@/lib/api/server';
import {buildPeriodPerformance} from '@/lib/mock/analytics';

export const dynamic = 'force-dynamic';

export async function GET(req: NextRequest) {
  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,
  );
}
