<?php

namespace Autogedal\TbiBank\Plugin;

use Autogedal\TbiBank\Model\ApplicationRegistry;
use Autogedal\TbiBank\Model\Environment;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\HTTP\Client\Curl;
use TbiBank\FusionPay\Model\Cryptor;

/** Keep the provider ID/token the original controller otherwise discards. */
class RegistrationResult
{
    public function __construct(private ApplicationRegistry $registry, private Environment $environment)
    {
    }

    public function afterPost(Curl $subject, $result, $uri, $params)
    {
        if (parse_url((string) $uri, PHP_URL_PATH) !== '/api/RegisterApplication') {
            return $result;
        }
        if ((string) $uri !== $this->environment->getOrigin() . '/api/RegisterApplication'
            || $subject->getStatus() !== 200
        ) {
            return $result;
        }
        $response = json_decode($subject->getBody(), true);
        if (!is_array($response) || !isset($response['error']) || (int) $response['error'] !== 0) {
            return $result;
        }
        $request = is_array($params) ? $params : json_decode((string) $params, true);
        $credentials = $this->environment->getCredentials();
        if (!is_array($request) || ($request['reseller_code'] ?? null) !== $credentials['reseller_code']
            || ($request['reseller_key'] ?? null) !== $credentials['reseller_key'] || !is_string($request['data'] ?? null)
        ) {
            throw new LocalizedException(__('The TBI application response could not be linked to this account.'));
        }
        $payload = json_decode(Cryptor::Decrypt($request['data'], $credentials['encryption_key']), true);
        if (!is_array($payload) || !is_scalar($payload['orderid'] ?? null)
            || !ctype_digit((string) ($response['order_id'] ?? '')) || !is_string($response['token'] ?? null)
        ) {
            throw new LocalizedException(__('The TBI application response is incomplete.'));
        }
        $this->registry->save((string) $payload['orderid'], (int) $response['order_id'], $response['token']);
        return $result;
    }
}
