/**
 * jobs/dailyReset.js
 * Reset API key counters at midnight UTC.
 * Also runs an alert sweep every 5 minutes for exhausted services.
 */

'use strict';

const cron       = require('node-cron');
const db         = require('../config/db');
const keyRotator = require('../services/keyRotator');

const dailyResetJob = {
  start() {
    // safety net in case the cron schedule isn't picked up
    cron.schedule('1 0 * * *', () => {
      console.log('[jobs] daily reset of API key counters');
      db.resetDailyKeyCounters();
    });
  },
};

const alertOnExhaustion = {
  _last: new Set(),
  start() {
    setInterval(async () => {
      try {
        const exhausted = keyRotator.exhaustedServices();
        const sig = exhausted.map(e => e.service).sort().join(',');
        if (sig && sig !== [...this._last].sort().join(',')) {
          this._last = new Set(exhausted.map(e => e.service));
          await keyRotator.alertIfExhausted();
        }
      } catch (e) {
        console.error('[jobs] alert sweep error:', e.message);
      }
    }, 5 * 60 * 1000); // every 5 minutes
  },
};

module.exports = { dailyResetJob, alertOnExhaustion };
