<?php

declare(strict_types=1);

namespace Autogedal\AwbRetry\Ui\Component\Listing\Column;

use Magento\Framework\Escaper;
use Magento\Framework\UrlInterface;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory as OrderCollectionFactory;
use Magento\Ui\Component\Listing\Columns\Column;

class OrderLink extends Column
{
    public function __construct(
        ContextInterface $context,
        UiComponentFactory $uiComponentFactory,
        private readonly OrderCollectionFactory $orderCollectionFactory,
        private readonly UrlInterface $urlBuilder,
        private readonly Escaper $escaper,
        array $components = [],
        array $data = []
    ) {
        parent::__construct($context, $uiComponentFactory, $components, $data);
    }

    public function prepareDataSource(array $dataSource): array
    {
        if (!isset($dataSource['data']['items'])) {
            return $dataSource;
        }

        $fieldName = $this->getData('name');
        $orderIds = [];

        foreach ($dataSource['data']['items'] as $item) {
            $orderId = (int) ($item[$fieldName] ?? 0);
            if ($orderId > 0) {
                $orderIds[] = $orderId;
            }
        }

        $incrementIds = [];
        if ($orderIds !== []) {
            $orderCollection = $this->orderCollectionFactory->create()
                ->addFieldToSelect(['entity_id', 'increment_id'])
                ->addFieldToFilter('entity_id', ['in' => array_values(array_unique($orderIds))]);

            foreach ($orderCollection as $order) {
                $incrementIds[(int) $order->getEntityId()] = (string) $order->getIncrementId();
            }
        }

        foreach ($dataSource['data']['items'] as &$item) {
            $orderId = (int) ($item[$fieldName] ?? 0);

            if ($orderId <= 0) {
                continue;
            }

            $label = $incrementIds[$orderId] ?? (string) $orderId;
            $url = $this->urlBuilder->getUrl('sales/order/view', ['order_id' => $orderId]);
            $item[$fieldName] = sprintf(
                '<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>',
                $this->escaper->escapeUrl($url),
                $this->escaper->escapeHtml($label)
            );
        }

        return $dataSource;
    }
}
