import { cleanOldLocations } from "../services/trackingService.js";

let cleanupTimeoutId = null;
let cleanupIntervalId = null;

const getDelayUntilNextRun = () => {
  const now = new Date();
  const next = new Date(now);
  next.setHours(2, 0, 0, 0);

  if (next.getTime() <= now.getTime()) {
    next.setDate(next.getDate() + 1);
  }

  return next.getTime() - now.getTime();
};

const runCleanup = async () => {
  try {
    await cleanOldLocations();
  } catch (error) {
    console.error("Tracking cleanup failed", error);
  }
};

export const initializeTrackingCleanupJob = () => {
  if (cleanupTimeoutId || cleanupIntervalId) {
    return;
  }

  cleanupTimeoutId = setTimeout(() => {
    runCleanup();
    cleanupIntervalId = setInterval(runCleanup, 24 * 60 * 60 * 1000);
  }, getDelayUntilNextRun());
};
