'use strict';

const path = require('path');
const fs = require('fs');
const { loadCredentials } = require('../utils/credentialStore');

const credentialCache = new Map();

function loadCredentialsIfPresent(filePath) {
  try {
    const stat = fs.statSync(filePath);
    const fingerprint = `${stat.mtimeMs}:${stat.size}`;
    const cached = credentialCache.get(filePath);
    if (cached?.fingerprint === fingerprint) return cached.value;

    const value = loadCredentials(filePath);
    credentialCache.set(filePath, { fingerprint, value });
    return value;
  } catch (err) {
    if (err.code === 'ENOENT' || err.message.includes('no encontrado')) {
      credentialCache.delete(filePath);
      return {};
    }
    throw err;
  }
}

function loadEncryptedDbCredentials(configPath = process.env.CONFIG_PATH || path.join(__dirname, '..', '..', 'config')) {
  const credentials = ['db.enc', 'connector-secret.enc', 'cloudflare-tunnel.enc']
    .map((filename) => loadCredentialsIfPresent(path.join(configPath, filename)));
  const merged = Object.assign({}, ...credentials);
  for (const [key, value] of Object.entries(merged)) {
    if (!process.env[key]) process.env[key] = value;
  }
  return merged;
}

module.exports = { loadEncryptedDbCredentials };
