<?php

namespace Fitsmart\PaypalParcels\ExternalService\ParcelPanel;

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

class ParcelpanelRequestDataPreparer implements RequestDataPreparerInterface
{
    public function preparePayload(int $noteId, \WC_Order $order): array
    {
        $orderId = $order->get_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 [
            'shipments' => [[
                'order_id' => $orderId,
                'tracking_number' => $trackingData['tracking_number'],
                'courier_code' => $trackingData['parcelpanel_carrier'] ?? '',
            ]]
        ];
    }
}
