import axios from 'axios';
import { logger } from '../utils/logger.js';

/**
 * Validuje JMAP credentials a vráti account ID
 * @param {string} email - Email address
 * @param {string} password - Email password
 * @returns {Promise<{accountId: string, session: object}>}
 */
export const validateJmapCredentials = async (email, password) => {
  const jmapServer = process.env.JMAP_SERVER;

  if (!jmapServer) {
    throw new Error('JMAP_SERVER premenná prostredia nie je nastavená');
  }

  try {
    const response = await axios.get(`${jmapServer}session`, {
      auth: {
        username: email,
        password: password,
      },
    });

    const session = response.data;

    // Získaj account ID z session
    const accountId = session.primaryAccounts?.['urn:ietf:params:jmap:mail'] ||
                      session.primaryAccounts?.['urn:ietf:params:jmap:core'] ||
                      Object.keys(session.accounts || {})[0];

    if (!accountId) {
      throw new Error('Nepodarilo sa získať JMAP account ID');
    }

    logger.success(`JMAP prihlasovacie údaje overené pre ${email}, accountId: ${accountId}`);

    return {
      accountId,
      session,
    };
  } catch (error) {
    logger.error(`Nepodarilo sa overiť JMAP prihlasovacie údaje pre ${email}`, error);

    if (error.response?.status === 401) {
      throw new Error('Nesprávne prihlasovacie údaje k emailu');
    }

    throw new Error('Nepodarilo sa overiť emailový účet');
  }
};
