/**
 * Normalize getSenderDetails(channel, orgUnitId) API response for a single channel.
 * Output shape matches cap-campaigns-v2 parseSenderDetails so UI can consume
 * domains with domainId, domainName, gsmSenders, emailSenders, emailRepliers, etc.
 *
 * Reference: cap-campaigns-v2 app/utils/parseSenderDetails.js
 * No cross-repo imports; logic aligned with campaigns domain structure.
 */

import get from 'lodash/get';
import { CHANNELS } from '../../constants';

const getSenderOptions = (contactInfo, key) =>
  (contactInfo || [])
    .filter((contactInfoItem) => contactInfoItem.type === key && contactInfoItem.valid)
    .sort((contact) => (contact.default ? -1 : 0));

/**
 * Parse raw API response for one channel into { domains: [...] }
 * @param {string} channel - SMS | EMAIL | WHATSAPP
 * @param {Object} response - API response (e.g. { entity: { SMS: [...] } } or { entity: [...] })
 * @returns {{ domains: Array }} - domains array compatible with campaigns DeliverySettingsV2
 */
export function parseSenderDetailsResponse(channel, response) {
  const entity = get(response, 'entity', response);
  if (!entity) {
    return { domains: [] };
  }

  // Single-channel API: entity may be { [channel]: [...] } or direct array
  let channelSenderDetails = get(entity, channel, null);
  if (channelSenderDetails == null && Array.isArray(entity)) {
    channelSenderDetails = entity;
  }
  if (!Array.isArray(channelSenderDetails)) {
    return { domains: [] };
  }

  const domains = [];

  channelSenderDetails.forEach((element) => {
    const { id: dgmId, priority, domainProperties = {} } = element;
    const {
      domainName,
      id = -1,
      contactInfo,
      connectionProperties: {
        sourceAccountIdentifier = '',
        wabaId = '',
        userid = '',
      } = {},
    } = domainProperties;

    const domain = {
      dgmId,
      domainName,
      domainId: id,
      priority: priority != null ? priority : 0,
    };

    if ([CHANNELS.SMS, CHANNELS.WHATSAPP].includes(channel)) {
      domain.cdmaSenders = getSenderOptions(contactInfo, 'cdma_sender_id');
      domain.gsmSenders = getSenderOptions(contactInfo, 'gsm_sender_id');
      domain.sourceAccountIdentifier =
        sourceAccountIdentifier || wabaId || userid || '';
    }

    if (channel === CHANNELS.EMAIL) {
      domain.emailSenders = getSenderOptions(contactInfo, 'sender_id');
      domain.emailRepliers = getSenderOptions(contactInfo, 'reply_to_id');
    }

    domains.push(domain);
  });

  // Sort by priority and dedupe by domainName (match campaigns behaviour)
  domains.sort((a, b) => (a.priority || 0) - (b.priority || 0));
  const deduped = domains.reduce((acc, domain) => {
    if (!acc.find((d) => d.domainName === domain.domainName)) {
      acc.push(domain);
    }
    return acc;
  }, []);

  return { domains: deduped };
}

export default parseSenderDetailsResponse;
