import pool from '../config/database';
import notificationService from '../services/notification.service';
import logger from '../utils/logger';

const INTERVAL_MS = 15 * 60 * 1000; // 15 minutes
let jobInterval: ReturnType<typeof setInterval> | null = null;
let isRunning = false;

async function runIssueReminderCheck(): Promise<void> {
  if (isRunning) {
    logger.warn('IssueReminderJob: previous run still in progress — skipping');
    return;
  }
  isRunning = true;
  try {
    // Find overdue issues that are not in a terminal status
    const result = await pool.query(`
      SELECT i.id, i.titel, i.faellig_am, i.erstellt_von, i.zugewiesen_an
      FROM issues i
      LEFT JOIN issue_statuses s ON s.schluessel = i.status
      WHERE i.faellig_am < NOW()
        AND (s.ist_abschluss = false OR s.ist_abschluss IS NULL)
    `);

    for (const row of result.rows) {
      // Notify the assignee, or the creator if no assignee
      const targetUserId = row.zugewiesen_an || row.erstellt_von;
      if (!targetUserId) continue;

      await notificationService.createNotification({
        user_id: targetUserId,
        typ: 'issue_ueberfaellig',
        titel: 'Issue überfällig',
        nachricht: `Issue "${row.titel}" ist überfällig`,
        schwere: 'warnung',
        link: `/issues/${row.id}`,
        quell_id: `issue-ueberfaellig-${row.id}`,
        quell_typ: 'issue_ueberfaellig',
      });
    }

    if (result.rows.length > 0) {
      logger.info(`IssueReminderJob: processed ${result.rows.length} overdue issues`);
    }
  } catch (error) {
    logger.error('IssueReminderJob: unexpected error', {
      error: error instanceof Error ? error.message : String(error),
    });
  } finally {
    isRunning = false;
  }
}

export function startIssueReminderJob(): void {
  if (jobInterval !== null) {
    logger.warn('Issue reminder job already running — skipping duplicate start');
    return;
  }
  // Run once after short delay, then repeat
  setTimeout(() => runIssueReminderCheck(), 60 * 1000);
  jobInterval = setInterval(() => runIssueReminderCheck(), INTERVAL_MS);
  logger.info('Issue reminder job scheduled (every 15 minutes)');
}

export function stopIssueReminderJob(): void {
  if (jobInterval !== null) {
    clearInterval(jobInterval);
    jobInterval = null;
  }
  logger.info('Issue reminder job stopped');
}
