const LAST_PICKUP_INFO_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;

function parseTimestamp(value) {
  if (!value) {
    return null;
  }
  const timestamp = value instanceof Date ? value.getTime() : new Date(value).getTime();
  return Number.isFinite(timestamp) ? timestamp : null;
}

function getStaleLastPickupStoreIds(config = [], now = Date.now()) {
  if (!Array.isArray(config)) {
    return [];
  }
  return config
    .filter((entry) => {
      if (!entry?.id || entry.hidden) {
        return false;
      }
      const lastPickupAt = parseTimestamp(entry.lastPickupAt);
      if (entry.lastPickupAt && (!lastPickupAt || lastPickupAt <= 0)) {
        return true;
      }
      const checkedAt = parseTimestamp(entry.lastPickupCheckedAt);
      return !checkedAt || now - checkedAt > LAST_PICKUP_INFO_MAX_AGE_MS;
    })
    .map((entry) => String(entry.id));
}

function parseLastFetchTimestamp(value) {
  if (typeof value === 'string') {
    if (value.trim() !== '' && Number.isFinite(Number(value))) {
      return parseLastFetchTimestamp(Number(value));
    }
    const timestamp = parseTimestamp(value);
    return timestamp && timestamp > 0 ? timestamp : null;
  }
  if (!Number.isFinite(Number(value))) {
    return null;
  }
  const numericValue = Number(value);
  if (numericValue <= 0) {
    return null;
  }
  return numericValue > 1e12 ? numericValue : numericValue * 1000;
}

function updateLastPickupInfo(entry, lastFetchValue, memberSinceValue, checkedAt = new Date()) {
  if (!entry || typeof entry !== 'object') {
    return false;
  }
  let changed = false;
  const checkedAtIso = new Date(checkedAt).toISOString();
  if (entry.lastPickupCheckedAt !== checkedAtIso) {
    entry.lastPickupCheckedAt = checkedAtIso;
    changed = true;
  }
  const lastFetchTimestamp = parseLastFetchTimestamp(lastFetchValue);
  if (lastFetchTimestamp !== null) {
    const lastPickupAt = new Date(lastFetchTimestamp).toISOString();
    if (entry.lastPickupAt !== lastPickupAt) {
      entry.lastPickupAt = lastPickupAt;
      changed = true;
    }
  } else if (entry.lastPickupAt) {
    delete entry.lastPickupAt;
    changed = true;
  }
  const memberSinceTimestamp = parseTimestamp(memberSinceValue);
  if (memberSinceTimestamp !== null && memberSinceTimestamp > 0) {
    const memberSinceAt = new Date(memberSinceTimestamp).toISOString();
    if (entry.memberSinceAt !== memberSinceAt) {
      entry.memberSinceAt = memberSinceAt;
      changed = true;
    }
  }
  return changed;
}

module.exports = {
  LAST_PICKUP_INFO_MAX_AGE_MS,
  getStaleLastPickupStoreIds,
  parseLastFetchTimestamp,
  updateLastPickupInfo
};
