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: 1440,
    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 ldapSyncTimer = null;

export function restartLdapSyncScheduler() {
  if (ldapSyncTimer) {
    clearInterval(ldapSyncTimer);
    ldapSyncTimer = null;
  }
  const cfg = loadIntegrations().ldap;
  if (!cfg.syncEnabled) return;
  const m = Math.max(0, Number(cfg.syncIntervalMinutes) || 0);
  if (m <= 0) return;
  ldapSyncTimer = setInterval(() => {
    performLdapSync(db, loadIntegrations, 'automatic').catch((err) =>
      console.error('LDAP auto-sync:', err),
    );
  }, m * 60 * 1000);
}
