<?php

namespace PaymentWebhooks\Gateway\Common;

use PaymentWebhooks\Infrastructure\Config;

final class PaymentDataResolver
{
    private array $jsonFields;
    private array $triggerArray;
    private string $gateway;
    private array $paymentConfig;

    public function __construct(string $gateway)
    {
        $config = Config::gateway($gateway) ?? [];
        $this->jsonFields = $config['json_fields'] ?? [];
        $this->triggerArray = $config['payment_collect_data_trigger'] ?? [];
        $this->gateway = $gateway;
        $this->paymentConfig = $config['payment_data'] ?? [];
    }

    public function shouldCollect(array $payload): bool
    {
        if (empty($this->triggerArray)) {
            return false;
        }

        foreach ($this->triggerArray as $fieldKey => $expected) {
            $path = $this->jsonFields[$fieldKey] ?? null;
            if (!$path) {
                return false;
            }
            $value = PayloadHelper::getByPath($payload, $path);
            if ((string) $value !== (string) $expected) {
                return false;
            }
        }
        return true;
    }

    public function collect(array $payload): array
    {
        return match ($this->gateway) {
            'paypal' => $this->collectPaypal($payload),
            'adyen'  => $this->collectAdyen($payload),
            default  => [],
        };
    }

    private function collectPaypal(array $payload): array
    {
        $idPath = $this->jsonFields['transaction_id'] ?? '';
        $transactionId = PayloadHelper::getByPath($payload, $idPath);
        return [
            'payment_method' => $this->paymentConfig['method'] ?? 'nuxt_paypal',
            'payment_method_title' => $this->paymentConfig['title'] ?? 'PayPal',
            'transaction_id' => is_scalar($transactionId) ? (string) $transactionId : '',
        ];
    }

    private function collectAdyen(array $payload): array
    {
        $slugPath = $this->jsonFields['payment_method_slug'] ?? '';
        $idPath = $this->jsonFields['transaction_id'] ?? '';
        $slug = PayloadHelper::getByPath($payload, $slugPath);
        $transactionId = PayloadHelper::getByPath($payload, $idPath);
        $slugStr = is_scalar($slug) ? (string) $slug : '';
        $methodPrefix = $this->paymentConfig['method_prefix'] ?? 'nuxt_adyen_';
        $titlePrefix = $this->paymentConfig['title_prefix'] ?? 'Adyen ';
        return [
            'payment_method' => $methodPrefix . $slugStr,
            'payment_method_title' => $titlePrefix . $slugStr,
            'transaction_id' => is_scalar($transactionId) ? (string) $transactionId : '',
        ];
    }
}
