const TTL_MS = Number(process.env.UPLOAD_SESSION_TTL_MS || 60 * 60 * 1000);

const store = new Map();

function saveSession(uploadId, payload) {
  const record = {
    ...payload,
    expiresAt: Date.now() + TTL_MS,
  };
  store.set(uploadId, record);
  setTimeout(() => {
    const cur = store.get(uploadId);
    if (cur === record) {
      store.delete(uploadId);
    }
  }, TTL_MS);
}

function getSession(uploadId) {
  if (!uploadId) {
    return null;
  }
  const v = store.get(uploadId);
  if (!v) {
    return null;
  }
  if (Date.now() > v.expiresAt) {
    store.delete(uploadId);
    return null;
  }
  return v;
}

function deleteSession(uploadId) {
  store.delete(uploadId);
}

module.exports = {
  saveSession,
  getSession,
  deleteSession,
};
