/**
 * Background service that polls the Teltonika device for new SMS messages
 * and stores them in the local database, triggering webhooks for new ones.
 */

const { getConfig, saveMessage, messageExistsByDeviceId } = require('./db');
const { dispatchWebhooks } = require('./webhookDispatcher');
const teltonika = require('./teltonika');
const log       = require('./logger');

let pollTimer = null;
let isPolling = false;

async function poll() {
  if (isPolling) return;

  const deviceIP = getConfig('device_ip');
  if (!deviceIP) {
    log.debug('Poller', 'No device IP configured – skipping poll');
    return;
  }

  isPolling = true;
  log.debug('Poller', 'Polling device for new messages…');
  try {
    const messages = await teltonika.readMessages();
    log.debug('Poller', `Fetched ${messages.length} message(s) from device`);

    for (const msg of messages) {
      // Only process inbox messages (received)
      if (msg.type !== 'inbox' && msg.type !== 'received') continue;
      if (!msg.id || !msg.sender || !msg.text) continue;

      // Skip messages we've already stored
      if (messageExistsByDeviceId(msg.id)) continue;

      const saved = saveMessage({
        direction:     'received',
        phone_number:  msg.sender,
        message:       msg.text,
        status:        'received',
        device_msg_id: msg.id,
      });

      log.info('Poller', `New SMS from ${msg.sender}: "${msg.text.substring(0, 50)}"`);

      // Dispatch webhooks asynchronously
      dispatchWebhooks('received', saved).catch(err => {
        log.error('Poller', 'Webhook dispatch error:', err.message);
      });
    }
  } catch (err) {
    // Downgrade connection-refused / timeout to WARNING to avoid log spam
    if (err.message?.includes('ECONNREFUSED') || err.message?.includes('timeout')) {
      log.warn('Poller', 'Device unreachable:', err.message);
    } else {
      log.error('Poller', 'Poll error:', err.message);
    }
  } finally {
    isPolling = false;
  }
}

function scheduleNext() {
  const interval = parseInt(getConfig('poll_interval') || '30', 10) * 1000;
  log.debug('Poller', `Next poll in ${interval / 1000}s`);
  pollTimer = setTimeout(async () => {
    await poll();
    scheduleNext();
  }, interval);
}

async function startPoller() {
  if (pollTimer) return;
  log.info('Poller', 'Starting SMS polling service');
  // Run first poll after 5 seconds to let the server initialize
  pollTimer = setTimeout(async () => {
    await poll();
    scheduleNext();
  }, 5_000);
}

function stopPoller() {
  if (pollTimer) {
    clearTimeout(pollTimer);
    pollTimer = null;
    log.info('Poller', 'Stopped');
  }
}

/**
 * Trigger an immediate poll (used after config changes).
 */
async function triggerPoll() {
  log.info('Poller', 'Manual poll triggered');
  await poll();
}

module.exports = { startPoller, stopPoller, triggerPoll };
