'use strict';

const logger = require('../utils/logger');
const { sendTunnelHeartbeat } = require('./syncClient');

function buildTunnelHeartbeatPayload(config) {
  const hasDomain = Boolean(config.localDomain || config.tunnelUrl);
  return {
    agent_id: config.agentId,
    tenant_id: config.tenantId,
    branch_id: config.branchId,
    connectorId: config.agentId,
    localDomain: config.localDomain || (config.tunnelUrl || '').replace(/^https?:\/\//i, '').replace(/\/+$/, '') || null,
    tunnelStatus: hasDomain ? 'online' : 'unknown',
    localAppStatus: 'online',
    public_local_portal_url: config.tunnelUrl || (config.localDomain ? `https://${config.localDomain}` : null),
    tunnel_status: hasDomain ? 'online' : 'unknown',
    tunnel_mode: 'cloudflare',
    tunnel_id: config.tunnelId || null,
    ingress_url: config.tunnelIngressUrl || null,
  };
}

function startTunnelStatus(config) {
  if (!config.tunnelEnabled) return null;

  async function report() {
    try {
      await sendTunnelHeartbeat(config, buildTunnelHeartbeatPayload(config));
    } catch (err) {
      logger.warn({ event: 'agent_tunnel_heartbeat_failed', error: err.message });
    }
  }

  report();
  const timer = setInterval(report, config.heartbeatIntervalSeconds * 1000);
  timer.unref?.();
  return timer;
}

module.exports = { startTunnelStatus, buildTunnelHeartbeatPayload };
