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

const CONFIG_DIR = path.join(__dirname, '..', 'config');
const CREDENTIAL_FILE = path.join(CONFIG_DIR, 'credentials.json');

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

function readStore() {
  ensureDir();
  if (!fs.existsSync(CREDENTIAL_FILE)) {
    writeJsonFile(CREDENTIAL_FILE, {}, { backup: false });
  }

  try {
    const parsed = readJsonFile(
      CREDENTIAL_FILE,
      {},
      (value) => value && typeof value === 'object' && !Array.isArray(value)
    );
    return parsed && typeof parsed === 'object' ? parsed : {};
  } catch (error) {
    console.error('Konnte Credential-Store nicht lesen:', error.message);
    return {};
  }
}

function writeStore(store) {
  ensureDir();
  writeJsonFile(CREDENTIAL_FILE, store);
}

function save(profileId, credentials) {
  if (!profileId || !credentials?.email || !credentials?.password) {
    return;
  }
  const store = readStore();
  store[profileId] = credentials;
  writeStore(store);
}

function remove(profileId) {
  if (!profileId) {
    return;
  }
  const store = readStore();
  if (store[profileId]) {
    delete store[profileId];
    writeStore(store);
  }
}

function loadAll() {
  return readStore();
}

function get(profileId) {
  if (!profileId) {
    return null;
  }
  const store = readStore();
  return store[profileId] || null;
}

module.exports = {
  save,
  remove,
  loadAll,
  get
};
