import { getIO } from './realtime.js';

const MAX_FEED = 40;
const DEDUPE_MS = 15_000;
const feed = [];

export function getDropFeed() {
  return feed.map(({ _fp, ...publicEvent }) => publicEvent);
}

function fingerprint(entry) {
  const ids = (entry.inventoryIds || [entry.item?.inventoryId]).filter(Boolean).sort();
  return [
    entry.username || '',
    entry.item?.id || '',
    String(entry.item?.valueCents ?? entry.item?.marketValue ?? ''),
    entry.count || 1,
    entry.openCount || 1,
    entry.respin ? 'respin' : 'open',
    ids.join(',') || `snap:${entry.item?.name || ''}`,
  ].join('|');
}

export function pushDrop(entry) {
  const fp = fingerprint(entry);
  const now = Date.now();

  // Ignore duplicate announces for the same open batch
  const dup = feed.find(
    (d) => d._fp === fp && now - new Date(d.at).getTime() < DEDUPE_MS
  );
  if (dup) return dup;

  const event = {
    id: `${now}-${Math.random().toString(36).slice(2, 8)}`,
    at: new Date().toISOString(),
    _fp: fp,
    ...entry,
  };
  feed.unshift(event);
  if (feed.length > MAX_FEED) feed.length = MAX_FEED;

  const io = getIO();
  if (io) {
    const { _fp, ...publicEvent } = event;
    io.to('feed').emit('feed:drop', publicEvent);
    return publicEvent;
  }
  const { _fp, ...publicEvent } = event;
  return publicEvent;
}

export function clearDropFeed() {
  feed.length = 0;
  const io = getIO();
  if (io) {
    io.to('feed').emit('feed:history', []);
  }
}
