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 runChecklistReminderCheck(): Promise<void> {
  if (isRunning) {
    logger.warn('ChecklistReminderJob: previous run still in progress — skipping');
    return;
  }
  isRunning = true;
  try {
    // Find overdue checklists (vehicles + equipment)
    const result = await pool.query(`
      SELECT cf.fahrzeug_id, cf.ausruestung_id, cf.vorlage_id, cf.naechste_faellig_am,
             f.bezeichnung AS fahrzeug_name,
             ar.name AS ausruestung_name,
             v.name AS vorlage_name
      FROM checklist_faelligkeit cf
      LEFT JOIN fahrzeuge f ON f.id = cf.fahrzeug_id AND f.deleted_at IS NULL
      LEFT JOIN ausruestung ar ON ar.id = cf.ausruestung_id
      JOIN checklist_vorlagen v ON v.id = cf.vorlage_id AND v.aktiv = true
      WHERE cf.naechste_faellig_am <= CURRENT_DATE
        AND (cf.fahrzeug_id IS NOT NULL OR cf.ausruestung_id IS NOT NULL)
        AND (cf.fahrzeug_id IS NULL OR f.id IS NOT NULL)
    `);

    if (result.rows.length === 0) return;

    // Find users who can execute checklists (Zeugmeister, Fahrmeister, Kommandant groups)
    const usersResult = await pool.query(`
      SELECT id FROM users
      WHERE authentik_groups && ARRAY['dashboard_zeugmeister', 'dashboard_fahrmeister', 'dashboard_kommando', 'dashboard_admin']::text[]
    `);

    const targetUserIds = usersResult.rows.map((r: any) => r.id);
    if (targetUserIds.length === 0) return;

    for (const row of result.rows) {
      const faelligDatum = new Date(row.naechste_faellig_am).toLocaleDateString('de-AT', {
        day: '2-digit', month: '2-digit', year: 'numeric',
      });

      const targetName = row.fahrzeug_name || row.ausruestung_name || 'Unbekannt';
      const quellId = row.fahrzeug_id
        ? `${row.fahrzeug_id}_${row.vorlage_id}`
        : `eq_${row.ausruestung_id}_${row.vorlage_id}`;

      // Notify responsible users (dedup handled by quell_id)
      for (const userId of targetUserIds) {
        await notificationService.createNotification({
          user_id: userId,
          typ: 'checklist_faellig',
          titel: `Checkliste überfällig: ${row.vorlage_name}`,
          nachricht: `Die Checkliste "${row.vorlage_name}" für ${targetName} war fällig am ${faelligDatum}`,
          schwere: 'warnung',
          link: `/checklisten`,
          quell_id: quellId,
          quell_typ: 'checklist_faellig',
        });
      }
    }

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

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

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