<?php

class ubvxEspEventAdapter implements EspEventAdapterInterface
{
    public function verifyRequest(array $server, string $rawBody): bool
    {
        if (isset($_GET['token'])) {
            $expected = (string)mh_cfg('MAILBEEZ_MLBZ_ESP_WEBHOOK_TOKEN', '');
            if ($expected == '') {
                return false;
            }
            return hash_equals($expected, (string)$_GET['token']);
        }
        return true;
    }

    public function normalizeEvent(array $payload): array
    {
        $classification = strtolower((string)$this->pick($payload, array('classification', 'type')));
        $eventType = ($classification == 'hard') ? 'hard_bounce' : (($classification == 'soft') ? 'soft_bounce' : 'unknown');
        $eventTime = $this->pick($payload, array('time', 'event_time'));
        if ($eventTime == null || $eventTime == '') {
            $eventTime = date('Y-m-d H:i:s');
        } else {
            $eventTime = date('Y-m-d H:i:s', strtotime(str_replace('T', ' ', (string)$eventTime)));
        }

        return array(
            'provider' => 'ubvx',
            'provider_event_id' => $this->pick($payload, array('reference', 'id', 'event_id')),
            'provider_message_id' => $this->pick($payload, array('reference', 'message_id')),
            'mailbeez_message_id' => $this->pick($payload, array('mailbeez_message_id', 'headers.X-MailBeez-Message-ID')),
            'event_type' => $eventType,
            'event_time' => $eventTime,
            'recipient_email' => (string)$this->pick($payload, array('address', 'recipient_email', 'recipient')),
            'severity' => ($eventType == 'hard_bounce') ? 'failed' : (($eventType == 'soft_bounce') ? 'warning' : 'info'),
            'bounce_type' => ($eventType == 'hard_bounce') ? 'H' : (($eventType == 'soft_bounce') ? 'S' : null),
            'bounce_code' => '',
            'reason' => (string)$this->pick($payload, array('reason')),
            'url' => null,
            'attempt_no' => null,
            'correlation_confidence' => 'unknown',
            'raw_payload' => $payload,
            'headers' => array(),
            'tags' => array(),
        );
    }

    public function connectionTest(): array
    {
        return array('result' => true, 'provider' => 'ubvx', 'message' => 'ok');
    }

    private function pick(array $payload, array $keys)
    {
        foreach ($keys as $key) {
            if (strpos($key, '.') === false) {
                if (isset($payload[$key])) {
                    return $payload[$key];
                }
                continue;
            }
            $segments = explode('.', $key);
            $value = $payload;
            foreach ($segments as $segment) {
                if (!is_array($value) || !array_key_exists($segment, $value)) {
                    $value = null;
                    break;
                }
                $value = $value[$segment];
            }
            if ($value !== null) {
                return $value;
            }
        }
        return null;
    }
}
