/**
 * Scheduled counter resets (UTC).
 */

import cron from 'node-cron'
import { emailStats } from '../services/database.mjs'
import { log } from '../middleware/logger.mjs'

export function startCounterJobs() {
  cron.schedule(
    '0 0 * * *',
    async () => {
      const t = new Date().toISOString()
      try {
        const n = await emailStats.resetDaily()
        log.info(`[cron] resetDaily at ${t} — updated ${n} email_stats documents`)
      } catch (e) {
        log.error('[cron] resetDaily failed', { error: e.message })
      }
    },
    { timezone: 'UTC' }
  )

  cron.schedule(
    '0 0 1 * *',
    async () => {
      const t = new Date().toISOString()
      try {
        const n = await emailStats.resetWeekly()
        log.info(`[cron] resetWeekly at ${t} — updated ${n} email_stats documents`)
      } catch (e) {
        log.error('[cron] resetWeekly failed', { error: e.message })
      }
    },
    { timezone: 'UTC' }
  )

  log.success('Counter cron jobs scheduled (daily 00:00 UTC, monthly week reset 1st 00:00 UTC)')
}
