import { NextResponse } from 'next/server';
import { withV1ErrorHandler } from '@server/middleware/v1Errors';
import { withApiKey, ApiKeyRequest } from '@server/middleware/withApiKey';
import { getDashboardStats, getRevenueSummary, type DashboardPeriod } from '@server/services/analytics.service';

const VALID_PERIODS: DashboardPeriod[] = ['today', '7days', 'month', 'lifetime'];

export const GET = withV1ErrorHandler(
  withApiKey(async (req: ApiKeyRequest) => {
    const url = new URL(req.url);
    const branchId = url.searchParams.get('branch_id') ?? undefined;
    const periodRaw = url.searchParams.get('period') ?? 'today';
    const period = (VALID_PERIODS.includes(periodRaw as DashboardPeriod) ? periodRaw : 'today') as DashboardPeriod;

    const [stats, revenue] = await Promise.all([
      getDashboardStats(req.apiKey.restaurantId, branchId, period),
      getRevenueSummary(req.apiKey.restaurantId, branchId),
    ]);
    return NextResponse.json({
      data: {
        period,
        branch_id: branchId ?? null,
        stats,
        revenue,
      },
    });
  }, { permission: 'analytics:read' })
);
