const fs = require('fs');
const path = require('path');
const { readJsonFile, writeJsonFile } = require('./jsonFileStore');

const SETTINGS_DIR = path.join(__dirname, '..', 'config');

const DEFAULT_USER_SETTINGS = {
  notifications: {
    ntfy: {
      enabled: false,
      topic: '',
      serverUrl: ''
    },
    telegram: {
      enabled: false,
      chatId: ''
    }
  }
};

function ensureDir() {
  if (!fs.existsSync(SETTINGS_DIR)) {
    fs.mkdirSync(SETTINGS_DIR, { recursive: true });
  }
}

function getSettingsPath(profileId = 'shared') {
  return path.join(SETTINGS_DIR, `${profileId}-notifications.json`);
}

function sanitizeBoolean(value) {
  return !!value;
}

function sanitizeString(value) {
  if (typeof value !== 'string') {
    if (value === null || value === undefined) {
      return '';
    }
    return String(value);
  }
  return value.trim();
}

function hydrateSettingsFile(profileId) {
  ensureDir();
  const filePath = getSettingsPath(profileId);
  if (!fs.existsSync(filePath)) {
    writeJsonFile(filePath, DEFAULT_USER_SETTINGS, { backup: false });
  }
  return filePath;
}

function readNotificationSettings(profileId) {
  const filePath = hydrateSettingsFile(profileId);
  try {
    const parsed = readJsonFile(
      filePath,
      DEFAULT_USER_SETTINGS,
      (value) => value && typeof value === 'object' && !Array.isArray(value)
    );
    return {
      notifications: {
        ntfy: {
          enabled: sanitizeBoolean(parsed?.notifications?.ntfy?.enabled),
          topic: sanitizeString(parsed?.notifications?.ntfy?.topic),
          serverUrl: sanitizeString(parsed?.notifications?.ntfy?.serverUrl)
        },
        telegram: {
          enabled: sanitizeBoolean(parsed?.notifications?.telegram?.enabled),
          chatId: sanitizeString(parsed?.notifications?.telegram?.chatId)
        }
      }
    };
  } catch (error) {
    console.error(`[NOTIFICATIONS] Konnte Einstellungen für ${profileId} nicht lesen:`, error.message);
    return JSON.parse(JSON.stringify(DEFAULT_USER_SETTINGS));
  }
}

function writeNotificationSettings(profileId, patch = {}) {
  const current = readNotificationSettings(profileId);
  const next = {
    notifications: {
      ntfy: {
        enabled: sanitizeBoolean(patch?.notifications?.ntfy?.enabled ?? current.notifications.ntfy.enabled),
        topic: sanitizeString(patch?.notifications?.ntfy?.topic ?? current.notifications.ntfy.topic),
        serverUrl: sanitizeString(
          patch?.notifications?.ntfy?.serverUrl ?? current.notifications.ntfy.serverUrl
        )
      },
      telegram: {
        enabled: sanitizeBoolean(
          patch?.notifications?.telegram?.enabled ?? current.notifications.telegram.enabled
        ),
        chatId: sanitizeString(
          patch?.notifications?.telegram?.chatId ?? current.notifications.telegram.chatId
        )
      }
    }
  };

  const filePath = hydrateSettingsFile(profileId);
  writeJsonFile(filePath, next);
  return next;
}

module.exports = {
  DEFAULT_USER_SETTINGS,
  readNotificationSettings,
  writeNotificationSettings
};
