import { getDb } from '@pintrush/db';
import { handleFeedback } from '@/lib/play/feedback-route';
import { clientIp, hashIp, SlidingWindowLimiter, utcDay } from '@/lib/rate-limit';
import { analyticsSalt } from '@/lib/server-env';

/**
 * POST /api/feedback — one-tap "Was that round fair?" votes from phones (pilot metric, spec §11).
 * Stored as AnalyticsEvent{kind: ROUND_FAIRNESS, venueId, props: {roundId, fair}}; answers 204.
 */

// A whole bar shares one Wi-Fi address and votes about once per ~5-minute round (≤ 500 players).
const perClient = new SlidingWindowLimiter(600, 10 * 60_000);
// Ceiling on stored votes per process, whatever addresses they come from.
const global = new SlidingWindowLimiter(20_000, 60 * 60_000);

export async function POST(request: Request): Promise<Response> {
  const now = Date.now();
  return handleFeedback(request, {
    now,
    clientKey: hashIp(clientIp(request.headers), analyticsSalt(), utcDay(now)),
    perClient,
    global,
    // The venue comes from the ACTIVE room, and only for a recent round actually played in it.
    findVenue: async (roomId, roundId, since) => {
      const round = await getDb().round.findFirst({
        where: { id: roundId, startedAt: { gte: new Date(since) }, gameSession: { roomId, room: { status: 'ACTIVE' } } },
        select: { gameSession: { select: { room: { select: { venueId: true } } } } },
      });
      return round?.gameSession.room.venueId ?? null;
    },
    record: async ({ venueId, roundId, fair }) => {
      await getDb().analyticsEvent.create({ data: { kind: 'ROUND_FAIRNESS', venueId, props: { roundId, fair } } });
    },
  });
}
