<?php

namespace App\Services;

/**
 * Normalizes an inbound webhook payload (arbitrary key names from whatever
 * external form/tool sent it) into Contact field names, by matching common
 * aliases after stripping case/spaces/punctuation - so "Email Address",
 * "email_address" and "EmailAddress" all resolve the same way.
 */
class WebhookFieldMapper
{
    public static function map(array $payload): array
    {
        $normalized = [];
        foreach ($payload as $key => $value) {
            if (is_string($key)) {
                $normalized[self::normalizeKey($key)] = $value;
            }
        }

        $result = [];
        foreach (ContactFieldRegistry::aliases() as $field => $aliases) {
            foreach ($aliases as $alias) {
                $value = $normalized[self::normalizeKey($alias)] ?? null;

                if (is_string($value) && trim($value) !== '') {
                    $result[$field] = trim($value);
                    break;
                }
            }
        }

        // Fall back to splitting a combined "name" field on the first space
        if (!isset($result['first_name']) && !isset($result['last_name'])) {
            $name = $normalized[self::normalizeKey('name')] ?? $normalized[self::normalizeKey('full_name')] ?? null;

            if (is_string($name) && trim($name) !== '') {
                [$first, $last] = array_pad(preg_split('/\s+/', trim($name), 2), 2, null);
                $result['first_name'] = $first;
                $result['last_name']  = $last;
            }
        }

        return $result;
    }

    private static function normalizeKey(string $key): string
    {
        return strtolower(preg_replace('/[^a-z0-9]/i', '', $key));
    }
}
