'use strict';

const crypto = require('crypto');

const PROTOCOL_VERSION = 'arkhon-agent-v1';

function nonce() {
  return crypto.randomBytes(24).toString('base64url');
}

function sha256(value) {
  return crypto.createHash('sha256').update(value || '').digest('hex');
}

function signRequest({ method, path, timestamp, nonce: requestNonce, body, secret }) {
  const bodyHash = sha256(body || '');
  const payload = [
    PROTOCOL_VERSION,
    String(method || 'GET').toUpperCase(),
    path || '/',
    String(timestamp),
    requestNonce,
    bodyHash,
  ].join('\n');
  return crypto.createHmac('sha256', secret).update(payload).digest('hex');
}

function authHeaders(config, options = {}) {
  const method = options.method || 'GET';
  const path = options.path || '/';
  const body = typeof options.body === 'string' ? options.body : (options.body ? JSON.stringify(options.body) : '');
  const timestamp = Date.now().toString();
  const requestNonce = nonce();
  const secret = config.agentKey || config.connectorSecret;
  const keyId = config.agentKeyId || config.agent_key_id || config.connectorKeyId || config.connector_key_id;
  const bodyHash = sha256(body || '');
  if (!keyId) throw new Error('agent_key_id requerido para firmar requests cloud');
  return {
    'content-type': 'application/json',
    'x-agent-id': config.agentId,
    'x-agent-key-id': keyId,
    'x-agent-timestamp': timestamp,
    'x-agent-nonce': requestNonce,
    'x-agent-body-sha256': bodyHash,
    'x-agent-signature': signRequest({ method, path, timestamp, nonce: requestNonce, body, secret }),
    'x-arkhon-protocol': PROTOCOL_VERSION,
  };
}

module.exports = { authHeaders, signRequest, PROTOCOL_VERSION };
