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';

// 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 } = req.session;
    const url = new URL(req.url);
    const bId = url.searchParams.get('branch_id') ?? 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 });
  })
);
