import { decryptPassword } from '../../utils/password.js';

/**
 * Get JMAP configuration - from email account or user object
 * @param {object} source - Email account object or user object with email credentials
 * @param {boolean} isEncrypted - Whether the password needs decryption (default: true for user, false for account)
 */
export const getJmapConfig = (source, isEncrypted = true) => {
  if (!source) {
    throw new Error('Source object is required');
  }

  // Check required fields
  const email = source.email;
  const password = source.emailPassword;
  const accountId = source.jmapAccountId;

  if (!email || !password || !accountId) {
    throw new Error('Email account je neuplny');
  }

  // Decrypt password if needed
  const decryptedPassword = isEncrypted ? decryptPassword(password) : password;

  return {
    server: process.env.JMAP_SERVER || 'https://mail.truemail.sk/jmap/',
    username: email,
    password: decryptedPassword,
    accountId: accountId,
  };
};

/**
 * Get JMAP configuration from email account object
 * NOTE: Expects emailPassword to be already decrypted (from getEmailAccountWithCredentials)
 * @deprecated Use getJmapConfig(emailAccount, false) instead
 */
export const getJmapConfigFromAccount = (emailAccount) => {
  return getJmapConfig(emailAccount, false);
};
