import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { getDashboardStats, getHourlyActivity, getChannelBreakdown, type DashboardPeriod } from '@server/services/analytics.service';
import { requirePlanFeature } from '@server/utils/features';

// getChannelBreakdown uses `created_at >= CURRENT_DATE - INTERVAL '1 day' * days`,
// which is inclusive on both ends. To get exactly N days ending today:
//   today (1 day)  → 0  (CURRENT_DATE - 0 = today only)
//   7 days         → 6  (6 prior days + today = 7)
//   30 days/month  → 29 (29 prior days + today = 30)
//   lifetime       → 1824 (≈5 years)
const PERIOD_TO_DAYS: Record<DashboardPeriod, number> = {
  today: 0,
  '7days': 6,
  month: 29,
  lifetime: 1824,
};

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId, branchId } = req.session;
    await requirePlanFeature(restaurantId!, 'analytics');
    const url = new URL(req.url);
    // Match the pattern used by /api/analytics/orders, /api/analytics/revenue,
    // /api/analytics/full, /api/customers, etc.: explicit ?branch_id=... wins,
    // otherwise fall back to the active branch on the session so the Agent
    // Overview reflects the branch the user picked in the top bar. Owners
    // viewing "All branches" have branchId=null → undefined → restaurant-wide.
    const bId = url.searchParams.get('branch_id') ?? branchId ?? undefined;
    const rawPeriod = url.searchParams.get('period') ?? 'today';
    const period: DashboardPeriod = (['today', '7days', 'month', 'lifetime'].includes(rawPeriod)
      ? rawPeriod
      : 'today') as DashboardPeriod;
    const channelDays = PERIOD_TO_DAYS[period];
    const [stats, hourly, channels] = await Promise.all([
      getDashboardStats(restaurantId!, bId, period),
      getHourlyActivity(restaurantId!, bId),
      getChannelBreakdown(restaurantId!, channelDays, bId),
    ]);
    return NextResponse.json({ stats, hourly, channels });
  })
);
