import db from './db.js';
import { performLdapSync } from './ldap-sync.js';

const DEFAULT_INTEGRATIONS = {
  ldap: {
    serverUrl: '',
    bindDn: '',
    bindPassword: '',
    searchBase: '',
    userSearchFilter: '',
    userFilter: '',
    usernameAttribute: 'sAMAccountName',
    firstNameAttribute: 'givenName',
    lastNameAttribute: 'sn',
    syncIntervalMinutes: 0,
    syncEnabled: false,
    syncNotes: '',
  },
  teamviewer: {
    bearerToken: '',
    notes: '',
  },
};

export function loadIntegrations() {
  const row = db.prepare('SELECT value FROM app_settings WHERE key = ?').get('integrations');
  const base = structuredClone(DEFAULT_INTEGRATIONS);
  if (!row?.value) return base;
  try {
    const s = JSON.parse(row.value);
    if (s.ldap && typeof s.ldap === 'object') Object.assign(base.ldap, s.ldap);
    const ld = base.ldap;
    if (!ld.userSearchFilter && ld.userFilter) ld.userSearchFilter = ld.userFilter;
    if (s.teamviewer && typeof s.teamviewer === 'object')
      Object.assign(base.teamviewer, s.teamviewer);
    const tv = base.teamviewer;
    if (!tv.bearerToken && tv.apiToken) tv.bearerToken = tv.apiToken;
    if (tv.notes == null && tv.apiNotes) tv.notes = tv.apiNotes;
    return base;
  } catch {
    return base;
  }
}

export function saveIntegrations(obj) {
  const json = JSON.stringify(obj);
  db.prepare(
    `INSERT INTO app_settings (key, value) VALUES ('integrations', ?)
     ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
  ).run(json);
}

let ldapSchedulerTimer = null;

/** Wie Stundenerfassung: alle 5 Minuten prüfen, ob eine Synchronisation fällig ist. */
export function restartLdapSyncScheduler() {
  if (ldapSchedulerTimer) {
    clearInterval(ldapSchedulerTimer);
    ldapSchedulerTimer = null;
  }
  ldapSchedulerTimer = setInterval(() => {
    const cfg = loadIntegrations().ldap;
    if (!cfg.syncEnabled) return;
    const intervalMin = Math.max(0, Number(cfg.syncIntervalMinutes) || 0);
    if (intervalMin <= 0) return;

    const row = db
      .prepare("SELECT value FROM app_settings WHERE key = 'ldap_last_sync_at'")
      .get();
    const lastSync = row?.value ? new Date(row.value) : null;
    const now = new Date();
    const syncIntervalMs = intervalMin * 60 * 1000;

    if (!lastSync || now - lastSync >= syncIntervalMs) {
      console.log('Starte automatische LDAP-Synchronisation…');
      performLdapSync(db, loadIntegrations, 'automatic')
        .then((r) => {
          if (r.skipped) return;
          if (r.ok) {
            console.log(
              `Automatische LDAP-Synchronisation abgeschlossen: ${r.usersSynced} Benutzer synchronisiert`,
            );
          } else {
            console.error('LDAP auto-sync:', r.error || r.errors);
          }
        })
        .catch((err) => console.error('LDAP auto-sync:', err));
    }
  }, 5 * 60 * 1000);
}
