import prisma from './prisma';

/** Minimum gap between lastActiveAt writes to avoid hammering the DB. */
const TOUCH_INTERVAL_MS = 2 * 60 * 1000;

const lastTouchByUser = new Map<string, number>();

/**
 * Record that a user is currently active. Throttled per process.
 */
export async function touchLastActive(userId: string | undefined | null) {
  if (!userId) return;

  const now = Date.now();
  const previous = lastTouchByUser.get(userId) ?? 0;
  if (now - previous < TOUCH_INTERVAL_MS) return;

  lastTouchByUser.set(userId, now);

  try {
    await prisma.user.update({
      where: { id: userId },
      data: { lastActiveAt: new Date(now) },
    });
  } catch (error) {
    // Do not fail the request if presence update fails
    console.error('Failed to update lastActiveAt:', error);
    lastTouchByUser.delete(userId);
  }
}

export const chatUserSelect = {
  id: true,
  firstName: true,
  lastName: true,
  avatarUrl: true,
  lastActiveAt: true,
} as const;
