<?php

namespace Fitsmart\PaypalParcels\ExternalService\PayPal;

use Fitsmart\PaypalParcels\Config;
use Fitsmart\PaypalParcels\Contract\RequestDataPreparerInterface;
use Fitsmart\PaypalParcels\ExternalService\TrackingNoteParser;

class PaypalRequestDataPreparer implements RequestDataPreparerInterface
{
    public function preparePayload(int $noteId, \WC_Order $order): array
    {
        $transactionId = $order->get_transaction_id();

        $noteStd = wc_get_order_note($noteId);
        if (!$noteStd instanceof \stdClass) {
            throw new \RuntimeException('No note object received');
        }

        $parser = new TrackingNoteParser();

        $trackingData = $parser->parse($noteStd->content, Config::getConfigPart('parse_data') ?? []);
        if (!$trackingData) {
            return [];
        }

        return [
            'trackers' => [
                array_filter([
                    'transaction_id' => $transactionId,
                    'tracking_number' => $trackingData['tracking_number'],
                    'tracking_url' => $trackingData['tracking_url'],
                    'carrier' => $trackingData['paypal_carrier'],
                    'carrier_name_other' => $trackingData['paypal_carrier_name_other'],
                    'status' => Config::getConfigPart('paypal')['status'] ?? '',
                ])
            ],
        ];
    }
}
