'use strict';

const { authHeaders } = require('../../agent/agentAuth');

const DEFAULT_TIMEOUT_MS = parseInt(process.env.ARKHON_SYNC_HTTP_TIMEOUT_MS || '15000', 10);

async function request(context, path, options = {}) {
  if (!context.cloudBaseUrl) throw new Error('ARKHON_CLOUD_BASE_URL no configurado');
  const body = options.body ? JSON.stringify(options.body) : undefined;
  const method = options.method || 'GET';
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), options.timeoutMs || context.httpTimeoutMs || DEFAULT_TIMEOUT_MS);
  try {
    const response = await fetch(`${context.cloudBaseUrl}${path}`, {
      method,
      headers: authHeaders({ agentId: context.connectorId, agentKeyId: context.connectorKeyId, agentKey: context.connectorSecret }, { method, path: path.split('?')[0], body: body || '' }),
      body,
      signal: controller.signal,
    });
    const text = await response.text();
    const data = text ? JSON.parse(text) : {};
    if (!response.ok) {
      const error = new Error(data.error || `HTTP ${response.status}`);
      error.status = response.status;
      error.data = data;
      throw error;
    }
    return data;
  } catch (err) {
    if (err.name === 'AbortError') {
      const timeout = new Error('sync_http_timeout');
      timeout.code = 'sync_http_timeout';
      throw timeout;
    }
    throw err;
  } finally {
    clearTimeout(timer);
  }
}

function handshake(context) {
  return request(context, '/api/sync/handshake', {
    method: 'POST',
    body: {
      connector_id: context.connectorId,
      device_id: context.deviceId,
      install_id: context.installId,
      version: context.version,
      branch_code: context.branchCode,
      capabilities: ['offline_queue', 'billing_qr_printing', 'softrestaurant_extractors'],
    },
  });
}

function pushBatch(context, batch) {
  return request(context, '/api/sync/push', { method: 'POST', body: batch });
}

function pullConfig(context, lastServerCheckpoint) {
  const query = lastServerCheckpoint ? `?last_server_checkpoint=${encodeURIComponent(lastServerCheckpoint)}` : '';
  return request(context, `/api/sync/pull${query}`);
}

function heartbeat(context, status) {
  return request(context, '/api/sync/heartbeat', { method: 'POST', body: status });
}

function licenseStatus(context, status) {
  return request(context, '/api/agent/license-status', { method: 'POST', body: status, timeoutMs: 10000 });
}

function redeemLicense(context, payload) {
  return request(context, '/api/agent/licenses/redeem', { method: 'POST', body: payload, timeoutMs: 15000 });
}

module.exports = { handshake, pushBatch, pullConfig, heartbeat, licenseStatus, redeemLicense };
