export function startPlazaTasks({
  pool,
  plazaRedis,
  recalculateHotScores,
  writebackPublications,
}) {
  const timers = [];

  const schedule = (fn, intervalMs, label) => {
    const run = async () => {
      try {
        await fn();
      } catch (error) {
        console.error(`Plaza task ${label} failed:`, error.message);
      }
    };
    void run();
    const timer = setInterval(run, intervalMs);
    timer.unref?.();
    timers.push(timer);
  };

  schedule(async () => {
    const result = await recalculateHotScores(pool);
    if (result.updated > 0) await plazaRedis.invalidateFeedCaches();
  }, 10 * 60 * 1000, 'hot_score');

  schedule(async () => {
    await plazaRedis.syncCountersToMySQL();
  }, 5 * 60 * 1000, 'redis_sync');

  schedule(async () => {
    await writebackPublications(pool);
  }, 60 * 60 * 1000, 'publication_writeback');

  return {
    stop() {
      for (const timer of timers) clearInterval(timer);
    },
  };
}

export async function writebackPublications(pool) {
  const now = Date.now();
  const [result] = await pool.query(
    `UPDATE h5_publish_records p
     JOIN plaza_posts pp ON pp.publication_id = p.id
     SET p.plaza_view_count = pp.view_count,
         p.plaza_like_count = pp.like_count
     WHERE pp.status = 'published'`,
  );
  return { updated: result.affectedRows ?? 0, at: now };
}
