import { Body, Controller, Get, Headers, HttpCode, Ip, Post, UseGuards } from "@nestjs/common";
import { Throttle } from "@nestjs/throttler";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
import { AnalyticsService } from "./analytics.service";
import { TrackViewDto } from "./dto/track-view.dto";

@Controller("analytics")
export class AnalyticsController {
  constructor(private readonly analytics: AnalyticsService) {}

  // Public — fired by every visitor's browser (see
  // frontend/src/components/layout/AnalyticsTracker.tsx), only after they've
  // accepted the cookie/tracking consent banner. No auth, same as any other
  // beacon-style tracking endpoint.
  // Unauthenticated beacon — cap it well above normal browsing so it can't
  // be used to flood the page_views table.
  @Throttle({ default: { limit: 60, ttl: 60_000 } })
  @Post("track")
  @HttpCode(204)
  async track(
    @Body() dto: TrackViewDto,
    @Headers("user-agent") userAgent?: string,
    // Behind a reverse proxy (likely on cPanel), the real client IP is in
    // X-Forwarded-For, not the socket's address — @Ip() only ever gives the
    // socket address, so this prefers the forwarded header when present.
    @Headers("x-forwarded-for") forwardedFor?: string,
    @Ip() socketIp?: string,
  ) {
    await this.analytics.track(dto, userAgent, forwardedFor || socketIp || "");
  }

  @UseGuards(JwtAuthGuard)
  @Get("summary")
  summary() {
    return this.analytics.summary();
  }
}
