import { createHmac, timingSafeEqual } from 'crypto';
import type { IncomingMessage, ServerResponse } from 'http';
import type { WebhookConfig } from '../config/schema.js';
import type { ChannelAdapter, ChannelStatus, InboundMessage, OutboundMessage } from '../channels/types.js';
import { auditLogger } from '../audit/index.js';

/** Minimal interface for the parts of ChannelRegistry we need. */
interface ChannelLookup {
  get(name: string): { send(peerId: string, message: OutboundMessage): Promise<void> } | undefined;
}

/** Read the full request body as a string. */
function readBody(req: IncomingMessage): Promise<string> {
  return new Promise((resolve, reject) => {
    const chunks: Buffer[] = [];
    req.on('data', (chunk: Buffer) => chunks.push(chunk));
    req.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')));
    req.on('error', reject);
  });
}

/** Verify HMAC-SHA256 signature from the X-Webhook-Signature header. */
function verifyHmac(body: string, secret: string, signature: string): boolean {
  const expected = createHmac('sha256', secret).update(body).digest('hex');
  const sig = signature.startsWith('sha256=') ? signature.slice(7) : signature;

  if (expected.length !== sig.length) {return false;}

  try {
    return timingSafeEqual(Buffer.from(expected, 'hex'), Buffer.from(sig, 'hex'));
  } catch {
    return false;
  }
}

/**
 * Render a message template with {{body}} and {{json.field}} placeholders.
 * - {{body}} is replaced with the raw request body.
 * - {{json.field}} accesses a top-level field from the parsed JSON body.
 */
function renderTemplate(template: string, body: string): string {
  let result = template.replace(/\{\{body\}\}/g, body);

  // Replace {{json.field}} placeholders
  let parsed: Record<string, unknown> | undefined;
  result = result.replace(/\{\{json\.([^}]+)\}\}/g, (_match, field: string) => {
    if (!parsed) {
      try {
        parsed = JSON.parse(body) as Record<string, unknown>;
      } catch {
        return '';
      }
    }
    const value = parsed[field];
    if (value === undefined || value === null) {return '';}
    return typeof value === 'string' ? value : JSON.stringify(value);
  });

  return result;
}

export class WebhookHandler implements ChannelAdapter {
  readonly name = 'webhook';
  private _status: ChannelStatus = 'disconnected';
  private messageHandler?: (msg: InboundMessage) => void;
  private webhooks: Map<string, WebhookConfig> = new Map();

  constructor(
    private readonly webhookConfigs: WebhookConfig[],
    private readonly channelLookup: ChannelLookup,
  ) {
    for (const webhook of webhookConfigs) {
      this.webhooks.set(webhook.name, webhook);
    }
  }

  get status(): ChannelStatus {
    return this._status;
  }

  async connect(): Promise<void> {
    this._status = 'connected';

    const enabledCount = this.webhookConfigs.filter(w => w.enabled).length;
    if (enabledCount > 0) {
      console.log(`WebhookHandler: ${enabledCount} webhook(s) registered`);
      auditLogger?.systemStart('WebhookHandler', { webhooks_enabled: enabledCount });
    }
  }

  async disconnect(): Promise<void> {
    this._status = 'disconnected';
    auditLogger?.systemStop('WebhookHandler');
  }

  async send(peerId: string, message: OutboundMessage): Promise<void> {
    // peerId is the webhook name — look up its output config
    const webhook = this.webhooks.get(peerId);
    if (!webhook) {
      console.warn(`No webhook found for '${peerId}'`);
      return;
    }

    const outputAdapter = this.channelLookup.get(webhook.output.channel);
    if (!outputAdapter) {
      console.warn(`Output channel '${webhook.output.channel}' not found for webhook '${peerId}'`);
      return;
    }

    await outputAdapter.send(webhook.output.peer, message);
  }

  onMessage(handler: (msg: InboundMessage) => void): void {
    this.messageHandler = handler;
  }

  /**
   * Handle an incoming HTTP webhook request.
   * Returns true if the webhook was found and processed, false otherwise.
   */
  async handleRequest(webhookName: string, req: IncomingMessage, res: ServerResponse): Promise<boolean> {
    const webhook = this.webhooks.get(webhookName);
    if (!webhook) {
      auditLogger?.webhookNotFound(webhookName);
      res.writeHead(404, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ error: 'Unknown webhook' }));
      return false;
    }

    if (!webhook.enabled) {
      auditLogger?.webhookDenied(webhookName, 'Webhook disabled');
      res.writeHead(404, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ error: 'Webhook disabled' }));
      return false;
    }

    const body = await readBody(req);

    // Verify HMAC if secret is configured
    const signatureVerified = !webhook.secret;
    if (webhook.secret) {
      const signature = req.headers['x-webhook-signature'] as string | undefined;
      const verified = signature ? verifyHmac(body, webhook.secret, signature) : false;
      if (!verified) {
        auditLogger?.webhookDenied(webhookName, 'Invalid HMAC signature');
        res.writeHead(401, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ error: 'Invalid signature' }));
        return false;
      }
    }

    // Render message template
    const text = renderTemplate(webhook.message, body);

    const msg: InboundMessage = {
      id: `webhook-${webhookName}-${Date.now()}`,
      channel: 'webhook',
      senderId: webhookName,
      senderName: `webhook:${webhookName}`,
      text,
      timestamp: Date.now(),
      metadata: { webhookName, body },
    };

    auditLogger?.webhookReceive({
      webhook_name: webhookName,
      body,
      signature_verified: signatureVerified,
      output_channel: webhook.output.channel,
      output_peer: webhook.output.peer,
    });

    this.messageHandler?.(msg);

    res.writeHead(202, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ accepted: true }));
    return true;
  }

  /** Get list of all webhook names (enabled and disabled). */
  getWebhookNames(): string[] {
    return Array.from(this.webhooks.keys());
  }
}

// Export helpers for testing
export { readBody as _readBody, verifyHmac as _verifyHmac, renderTemplate as _renderTemplate };
