import 'server-only';
import { getFirestore, FieldValue } from 'firebase-admin/firestore';
import { getFirebaseAdmin } from '@/lib/firebase-admin';

const DEBOUNCE_MS = 5 * 60 * 1000; // 5분
const lastUpdateMap = new Map<string, number>(); // uid → last update timestamp

/**
 * 사용자 활동 추적 유틸리티
 * Firestore users/{uid}.lastActiveAt 필드를 갱신하되,
 * 인메모리 Map 기반 5분 디바운스를 적용해 Firestore write 비용을 최소화한다.
 */
export function trackActivity(uid: string): void {
    const now = Date.now();
    const lastUpdated = lastUpdateMap.get(uid);

    if (lastUpdated !== undefined && now - lastUpdated < DEBOUNCE_MS) {
        return; // 5분 이내 재호출 시 스킵
    }

    lastUpdateMap.set(uid, now);

    getFirebaseAdmin();
    const db = getFirestore();
    db.collection('users')
        .doc(uid)
        .update({ lastActiveAt: FieldValue.serverTimestamp() })
        .catch(() => {
            lastUpdateMap.delete(uid); // 다음 요청에서 재시도할 수 있도록 초기화
        });
}
