const axios = require('axios');
const fs = require('fs');
const FormData = require('form-data');
const { pool } = require('../../config/database');
const { logInfo, logError } = require('../../core/whatsapp/LogContext');

const buildHeaders = (accessToken) => ({
  'Authorization': `Bearer ${accessToken}`,
  'Content-Type': 'application/json'
});

const sendCloudRequest = async (account, payload) => {
  const response = await axios.post(
    `https://graph.facebook.com/v18.0/${account.phone_number_id}/messages`,
    payload,
    { headers: buildHeaders(account.access_token) }
  );
  const messageId = response?.data?.messages?.[0]?.id || null;
  return { messageId };
};

const uploadCloudMedia = async (account, media) => {
  const formData = new FormData();
  formData.append('file', fs.createReadStream(media.filePath), {
    filename: media.fileName,
    contentType: media.mimeType
  });
  formData.append('type', media.mimeType);
  formData.append('messaging_product', 'whatsapp');

  const response = await axios.post(
    `https://graph.facebook.com/v18.0/${account.phone_number_id}/media`,
    formData,
    {
      headers: {
        'Authorization': `Bearer ${account.access_token}`,
        ...formData.getHeaders()
      },
      timeout: 45000,
      maxContentLength: 50 * 1024 * 1024,
      maxBodyLength: 50 * 1024 * 1024
    }
  );
  return response?.data?.id || null;
};

const resolveAccount = async (tenantId, accountId) => {
  const [rows] = await pool.execute(
    'SELECT * FROM whatsapp_cloud_accounts WHERE id = ? AND tenant_id = ? LIMIT 1',
    [accountId, tenantId]
  );
  return rows?.[0] || null;
};

const send = async ({ tenantId, item, metadata }) => {
  const accountId = metadata.accountId;
  const logBase = {
    tenant_id: tenantId,
    message_id: item.id,
    module: 'cloud_sender',
    event: 'send'
  };

  if (!accountId) {
    logError('Cloud send failed: missing accountId', {
      ...logBase,
      step: 'validate',
      error: 'Missing accountId'
    });
    return { success: false, error: 'Missing accountId' };
  }

  const account = await resolveAccount(tenantId, accountId);
  if (!account?.access_token || !account?.phone_number_id) {
    logError('Cloud send failed: account invalid', {
      ...logBase,
      step: 'resolve_account',
      error: 'Account not found or missing credentials'
    });
    return { success: false, error: 'Account not found or missing credentials' };
  }

  const to = item.phone_number;
  const type = item.message_type || 'text';
  const payload = metadata.payload || null;

  try {
    if (type === 'text') {
      const bodyText = item.content || '';
      const messagePayload = {
        messaging_product: 'whatsapp',
        to,
        type: 'text',
        text: { body: bodyText }
      };
      const { messageId } = await sendCloudRequest(account, messagePayload);
      logInfo('Cloud text sent', { ...logBase, step: 'sent' });
      return { success: true, messageId };
    }

    if (type === 'reaction' && payload?.reaction) {
      const messagePayload = {
        messaging_product: 'whatsapp',
        to,
        type: 'reaction',
        reaction: payload.reaction
      };
      const { messageId } = await sendCloudRequest(account, messagePayload);
      logInfo('Cloud reaction sent', { ...logBase, step: 'sent' });
      return { success: true, messageId };
    }

    if (type === 'interactive' && payload?.interactive) {
      const messagePayload = {
        messaging_product: 'whatsapp',
        to,
        type: 'interactive',
        interactive: payload.interactive
      };
      const { messageId } = await sendCloudRequest(account, messagePayload);
      logInfo('Cloud interactive sent', { ...logBase, step: 'sent' });
      return { success: true, messageId };
    }

    if (type === 'products' && payload?.interactive) {
      const messagePayload = {
        messaging_product: 'whatsapp',
        to,
        type: 'interactive',
        interactive: payload.interactive
      };
      const { messageId } = await sendCloudRequest(account, messagePayload);
      logInfo('Cloud products sent', { ...logBase, step: 'sent' });
      return { success: true, messageId };
    }

    if (type === 'cta' && payload?.interactive) {
      const messagePayload = {
        messaging_product: 'whatsapp',
        to,
        type: 'interactive',
        interactive: payload.interactive
      };
      const { messageId } = await sendCloudRequest(account, messagePayload);
      logInfo('Cloud CTA sent', { ...logBase, step: 'sent' });
      return { success: true, messageId };
    }

    if (type === 'media' && payload?.media) {
      const mediaId = await uploadCloudMedia(account, payload.media);
      if (!mediaId) {
        return { success: false, error: 'Media upload failed' };
      }
      const mediaType = payload.media.mediaType;
      const messagePayload = {
        messaging_product: 'whatsapp',
        to,
        type: mediaType,
        [mediaType]: {
          id: mediaId
        }
      };
      if (payload.media.caption && mediaType !== 'audio') {
        messagePayload[mediaType].caption = payload.media.caption;
      }
      const { messageId } = await sendCloudRequest(account, messagePayload);
      logInfo('Cloud media sent', { ...logBase, step: 'sent' });
      return { success: true, messageId };
    }

    if (payload?.raw) {
      const { messageId } = await sendCloudRequest(account, payload.raw);
      logInfo('Cloud raw payload sent', { ...logBase, step: 'sent' });
      return { success: true, messageId };
    }

    return { success: false, error: 'Unsupported message type' };
  } catch (error) {
    logError('Cloud send error', {
      ...logBase,
      step: 'error',
      error: error.message || String(error)
    });
    return { success: false, error: error.message || String(error) };
  }
};

module.exports = { send };
