/**
 * Nightly Forecast Grant Worker
 * Runs at 2:00 AM ET (7:00 AM UTC winter / 6:00 AM UTC summer)
 * Batch-resets daily_free_forecasts for eligible users.
 * This is a BACKUP — ensureDailyGrant() handles the primary lazy path.
 *
 * Cron: 0 7 * * * (7 AM UTC ≈ 2 AM ET standard time)
 * Usage: npx ts-node src/workers/nightly-forecast-grant.ts
 */

import pool from '../db';
import { DAILY_FORECAST_GRANT } from '../models/user';
import { recordLedgerEntry } from '../models/ledger';

async function run() {
  const todayET = new Date().toLocaleDateString('en-CA', { timeZone: 'America/New_York' });

  console.log(`[nightly-forecast-grant] Starting for ET date: ${todayET}`);

  // Find eligible users who haven't been reset today.
  const { rows: users } = await pool.query(
    `SELECT u.id
     FROM rm_users u
     WHERE u.email_verified = TRUE
       AND COALESCE(u.signup_bonus_forecasts, 0) = 0
       AND COALESCE(u.survey_bonus_forecasts, 0) = 0
       AND EXISTS (
         SELECT 1
         FROM rm_survey_responses s
         WHERE s.user_id = u.id
       )
       AND (u.last_reset_date_pacific IS NULL OR u.last_reset_date_pacific < $1::date)`,
    [todayET]
  );

  console.log(`[nightly-forecast-grant] Found ${users.length} users to grant`);

  let granted = 0;
  for (const user of users) {
    try {
      const { rowCount } = await pool.query(
        `UPDATE rm_users SET daily_free_forecasts = $3, last_reset_date_pacific = $1, updated_at = NOW()
         WHERE id = $2 AND (last_reset_date_pacific IS NULL OR last_reset_date_pacific < $1::date)`,
        [todayET, user.id, DAILY_FORECAST_GRANT]
      );
      if (rowCount && rowCount > 0) {
        await recordLedgerEntry(user.id, DAILY_FORECAST_GRANT, 'DAILY_GRANT', DAILY_FORECAST_GRANT, { date: todayET, source: 'nightly_batch' });
        granted++;
      }
    } catch (err) {
      console.error(`[nightly-forecast-grant] Error granting to ${user.id}:`, err);
    }
  }

  console.log(`[nightly-forecast-grant] Granted daily forecasts to ${granted} users`);
  await pool.end();
  process.exit(0);
}

run().catch((err) => {
  console.error('[nightly-forecast-grant] Fatal error:', err);
  process.exit(1);
});
