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

/**
 * Make JMAP API request
 */
export const jmapRequest = async (jmapConfig, methodCalls) => {
  try {
    const response = await axios.post(
      jmapConfig.server,
      {
        using: ['urn:ietf:params:jmap:core', 'urn:ietf:params:jmap:mail'],
        methodCalls,
      },
      {
        auth: {
          username: jmapConfig.username,
          password: jmapConfig.password,
        },
        headers: {
          'Content-Type': 'application/json',
        },
      }
    );
    return response.data;
  } catch (error) {
    logger.error('JMAP požiadavka zlyhala', error);
    throw new Error(`JMAP požiadavka zlyhala: ${error.message}`);
  }
};

/**
 * Get user's mailboxes (Inbox, Sent, etc.)
 */
export const getMailboxes = async (jmapConfig) => {
  try {
    const response = await jmapRequest(jmapConfig, [
      [
        'Mailbox/get',
        {
          accountId: jmapConfig.accountId,
        },
        'mailbox1',
      ],
    ]);

    return response.methodResponses[0][1].list;
  } catch (error) {
    logger.error('Nepodarilo sa získať priečinky', error);
    throw error;
  }
};

/**
 * Get user identities (for sending emails)
 */
export const getIdentities = async (jmapConfig) => {
  try {
    const response = await jmapRequest(jmapConfig, [
      [
        'Identity/get',
        {
          accountId: jmapConfig.accountId,
        },
        'identity1',
      ],
    ]);

    return response.methodResponses[0][1].list;
  } catch (error) {
    logger.error('Nepodarilo sa získať identity', error);
    throw error;
  }
};
