<?php

declare(strict_types=1);

use Magento\Framework\App\Bootstrap;
use Magento\Sales\Api\CreditmemoServiceInterface;

require __DIR__ . '/../../../../../app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

$response = $objectManager->get(Magento\Framework\App\ResponseInterface::class);
$state = $objectManager->get(Magento\Framework\App\State::class);
$state->setAreaCode(Magento\Framework\App\Area::AREA_ADMINHTML);
$externalCreditMemo = $objectManager->create(FiloBlu\Esb\Api\ExternalCreditmemoInterface::class);

$creditMemoData = $objectManager->create(Magento\Sales\Api\Data\CreditmemoInterface::class);

$creditMemoExtensionAttributesFacory = $objectManager->create(Magento\Sales\Api\Data\CreditmemoExtensionInterfaceFactory::class);
$creditMemoExtensionAttributes = $creditMemoExtensionAttributesFacory->create();
$creditMemoExtensionAttributes->setOrderIncrementId('00000040311');
$creditMemoExtensionAttributes->setDocumentType('creditmemo');

$creditMemoData->setExtensionAttributes($creditMemoExtensionAttributes);
$creditMemoData->setIncrementId('CM100000001');
$creditMemoData->setGrandTotal(40.50);

$creditmemoItems = [
    [
        'sku' => '11.10.266.18.S',
        'qty' => 1
    ],
];
$creditMemoData->setItems($creditmemoItems);

try {
    $response = $externalCreditMemo->save($creditMemoData);
    echo "Credit memo saved successfully!";
    echo "Response: " . $response->getMessage();  // Assuming your response object has a `getMessage()` method
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
