import { AlchemyWebhookNormalizationService } from "../../services/AlchemyWebhookNormalizationService";
import { AlchemyWebhookPayloadValidator } from "../../services/AlchemyWebhookPayloadValidator";
import { AlchemyWebhookVerificationService } from "../../services/AlchemyWebhookVerificationService";
import { IWebhookProcessorPort, WebhookProcessResult } from "../ProviderPorts";

/**
 * Alchemy implementation of IWebhookProcessorPort.
 * Sequences the three internal Alchemy pipeline steps:
 *   1. HMAC signature verification (rejects bad requests)
 *   2. Payload structural validation (rejects malformed payloads)
 *   3. Normalisation to canonical DepositEvents
 *
 * Routes call this port — they remain unaware of Alchemy specifics.
 */
export class AlchemyWebhookProcessorAdapter implements IWebhookProcessorPort {
  constructor(
    private readonly verificationService: AlchemyWebhookVerificationService,
    private readonly payloadValidator: AlchemyWebhookPayloadValidator,
    private readonly normalizationService: AlchemyWebhookNormalizationService
  ) {}

  async process(
    body: unknown,
    headers: Record<string, string | string[] | undefined>,
    rawBody: string | undefined
  ): Promise<WebhookProcessResult> {
    const verified = this.verificationService.verify(body, headers, rawBody);
    console.log("Webhook payload verified successfully", verified);
    const validated = this.payloadValidator.validate(verified);
    const { events, metrics } = await this.normalizationService.normalize(validated);
    return { events, metrics };
  }
}
