const { getAllSchedules } = require('../repositories/auditSchedulesRepository');
const { getReminderOccurrenceDate } = require('../utils/auditScheduleRecurrence');
const { buildAuditReminderMailBody, sendTicketEmail } = require('./emailService');

const sentKeys = new Set();
let lastClearDate = '';

function clearSentKeysIfNewDay() {
  const todayKey = new Date().toISOString().slice(0, 10);
  if (todayKey !== lastClearDate) {
    sentKeys.clear();
    lastClearDate = todayKey;
  }
}

async function sendReminderForSchedule(schedule, occurrenceDate) {
  const toEmail = schedule.assigned_to_email;
  if (!toEmail) return { skipped: true, reason: 'no email' };

  const occurrence = new Date(`${occurrenceDate}T12:00:00`);
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  occurrence.setHours(0, 0, 0, 0);
  const daysUntil = Math.max(0, Math.ceil((occurrence - today) / (24 * 60 * 60 * 1000)));

  const htmlBody = buildAuditReminderMailBody({
    auditName: schedule.audit_name,
    scheduledDate: occurrenceDate,
    daysUntil,
    assignedToName: schedule.assigned_to_name,
  });

  return sendTicketEmail({
    to: toEmail,
    subject: `Reminder: Audit scheduled – ${schedule.audit_name}`,
    htmlBody,
  });
}

async function runAuditScheduleReminders() {
  clearSentKeysIfNewDay();
  const schedules = await getAllSchedules();
  const results = { checked: schedules.length, sent: 0, skipped: 0, failed: 0 };

  for (const schedule of schedules) {
    const occurrenceDate = getReminderOccurrenceDate(schedule);
    if (!occurrenceDate) continue;

    const key = `${schedule.id}:${occurrenceDate}`;
    if (sentKeys.has(key)) {
      results.skipped += 1;
      continue;
    }

    try {
      const outcome = await sendReminderForSchedule(schedule, occurrenceDate);
      sentKeys.add(key);
      if (outcome?.sent) results.sent += 1;
      else results.skipped += 1;
    } catch (err) {
      console.warn('[auditScheduleReminder] Failed for schedule', schedule.id, err.message);
      results.failed += 1;
    }
  }

  if (results.sent > 0 || results.failed > 0) {
    console.log('[auditScheduleReminder]', results);
  }
  return results;
}

/** Run once on startup (after a short delay) and then every 24 hours. */
function startAuditScheduleReminderJob() {
  const enabled = String(process.env.AUDIT_SCHEDULE_REMINDERS_ENABLED ?? 'true').toLowerCase();
  if (enabled === 'false' || enabled === '0' || enabled === 'no') {
    console.log('[auditScheduleReminder] Automatic reminders disabled (AUDIT_SCHEDULE_REMINDERS_ENABLED=false)');
    return;
  }

  const run = () => {
    runAuditScheduleReminders().catch((err) => {
      console.warn('[auditScheduleReminder] Job error:', err.message);
    });
  };

  setTimeout(run, 30_000);
  setInterval(run, 24 * 60 * 60 * 1000);
  console.log('[auditScheduleReminder] Daily reminder job scheduled');
}

module.exports = {
  runAuditScheduleReminders,
  startAuditScheduleReminderJob,
};
