<?php
namespace EasyChat\Library;

class CustomerIdentityResolver {
    public function hashForMessengerContact(array $contact): string {
        $provider = strtolower(trim((string)($contact['provider'] ?? '')));
        $channel_id = (int)($contact['channel_id'] ?? 0);
        $external_user_id = trim((string)($contact['external_user_id'] ?? ''));
        $metadata = $this->metadata((string)($contact['metadata_json'] ?? ''));

        return $this->hashForContactParts($provider, $channel_id, $external_user_id, $metadata);
    }

    public function hashForContactParts(string $provider, int $channel_id, string $external_user_id, array $metadata): string {
        $provider = strtolower(trim($provider));
        if ($provider === '' || $channel_id <= 0) {
            return '';
        }

        $identity_kind = 'user';
        $identity_value = $this->cleanIdentityValue($external_user_id);

        if ($this->isMarketplaceDialogProvider($provider)) {
            $identity_kind = 'counterparty';
            $identity_value = $this->marketplaceCounterpartyId($metadata);
        }

        if ($identity_value === '') {
            return '';
        }

        return hash('sha256', $provider . '|' . $channel_id . '|' . $identity_kind . '|' . $identity_value);
    }

    public function metadata(string $json): array {
        $json = trim($json);
        if ($json === '') {
            return [];
        }

        $decoded = json_decode($json, true);
        return is_array($decoded) ? $decoded : [];
    }

    private function marketplaceCounterpartyId(array $metadata): string {
        foreach (['counterparty_author_id', 'buyer_user_id', 'buyer_id', 'customer_user_id', 'customer_id', 'author_id'] as $key) {
            $value = $this->cleanIdentityValue((string)($metadata[$key] ?? ''));
            if ($value !== '') {
                return $value;
            }
        }
        return '';
    }

    private function isMarketplaceDialogProvider(string $provider): bool {
        return in_array($provider, ['avito', 'youla', 'yula', 'marketplace'], true);
    }

    private function cleanIdentityValue(string $value): string {
        $value = trim($value);
        if ($value === '') {
            return '';
        }

        return substr($value, 0, 128);
    }
}
