import { NextRequest, NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { getKpis } from '@/lib/services/dashboard.service';
import { parseRangeSlug, rangeToBounds } from '@/lib/analytics/range';

/**
 * GET /api/v1/dashboard/kpis
 * GET /api/v1/dashboard/kpis?range=7d|30d|90d|today|custom-<from>-<to>
 *
 * Without `range`: returns the all-time pipeline snapshot. With
 * `range`: scopes the pipeline-value calculation to interests created
 * inside the window so the headline reflects "what was added to the
 * pipeline this period" rather than the cumulative book.
 */
export const GET = withAuth(
  withPermission('reports', 'view_dashboard', async (req: NextRequest, ctx) => {
    const url = new URL(req.url);
    const rangeSlug = url.searchParams.get('range');
    const range = rangeSlug ? parseRangeSlug(rangeSlug) : null;
    const bounds = range ? rangeToBounds(range) : null;
    const result = await getKpis(ctx.portId, bounds);
    // L34 carve-out: deliberate bare-shape response (NOT the `{ data }`
    // envelope). The dashboard widgets read these fields off the root of
    // the JSON; wrapping them would break the consumers. Left as-is.
    return NextResponse.json(result);
  }),
);
