<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\Shipment\Grid;

use InPost\International\Api\Shipment\Model\Parcel\DimensionUnit;
use InPost\International\Api\Shipment\Model\Parcel\WeightUnit;
use InPost\International\Api\Shipment\ShipmentType;
use InPost\International\Api\Tracking\TrackingEvent;
use InPost\International\Carrier\CarrierType;
use InPost\International\Shipment\ShippingMethod;
use InPost\International\Shipment\TrackingUrlGenerator;
use PrestaShop\PrestaShop\Core\Grid\Data\Factory\GridDataFactoryInterface;
use PrestaShop\PrestaShop\Core\Grid\Data\GridData;
use PrestaShop\PrestaShop\Core\Grid\Data\GridDataInterface;
use PrestaShop\PrestaShop\Core\Grid\Record\RecordCollection;
use PrestaShop\PrestaShop\Core\Grid\Search\SearchCriteriaInterface;
use PrestaShop\PrestaShop\Core\Localization\Locale;
use PrestaShop\PrestaShop\Core\Localization\LocaleInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

if (!defined('_PS_VERSION_')) {
    exit;
}

final class ShipmentGridDataFactory implements GridDataFactoryInterface
{
    /**
     * @var GridDataFactoryInterface
     */
    private $dataFactory;

    /**
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * @var Locale
     */
    private $locale;

    /**
     * @param Locale $locale
     */
    public function __construct(GridDataFactoryInterface $dataFactory, TranslatorInterface $translator, LocaleInterface $locale)
    {
        $this->dataFactory = $dataFactory;
        $this->translator = $translator;
        $this->locale = $locale;
    }

    public function getData(SearchCriteriaInterface $searchCriteria): GridDataInterface
    {
        $data = $this->dataFactory->getData($searchCriteria);

        $records = array_map([$this, 'modifyRecord'], $data->getRecords()->all());

        return new GridData(
            new RecordCollection($records),
            $data->getRecordsTotal(),
            $data->getQuery()
        );
    }

    private function modifyRecord(array $record): array
    {
        [$languageCode] = explode('-', $this->locale->getCode());
        $shipmentType = ShipmentType::from($record['type']);

        $record['shipping_cost'] = $this->formatShippingCost($record);
        $record['service'] = CarrierType::fromShipmentType($shipmentType)->trans($this->translator);
        $record['parcel_dimensions'] = $this->formatDimensions($record);
        $record['parcel_weight'] = $this->formatWeight($record);
        $record['shipping_method'] = ShippingMethod::fromShipmentType($shipmentType)->trans($this->translator);
        $record['tracking_url'] = TrackingUrlGenerator::generate($record['tracking_number'], $languageCode);
        $record['has_pickup_order'] = $this->getPickupOrderStatus($record, $shipmentType);
        $record['status'] = $this->formatStatus($record['status']);

        return $record;
    }

    private function formatShippingCost(array $record): string
    {
        if (!isset($record['order_currency'])) {
            return $this->formatNumber($record['shipping_cost']);
        }

        return $this->locale->formatPrice($record['shipping_cost'], $record['order_currency']);
    }

    private function formatDimensions(array $record): string
    {
        $unit = DimensionUnit::from($record['parcel_length_unit']);

        return sprintf(
            '%sｘ%sｘ%s %s',
            $this->formatNumber($record['parcel_length']),
            $this->formatNumber($record['parcel_width']),
            $this->formatNumber($record['parcel_height']),
            $unit->getSymbol()
        );
    }

    private function formatWeight(array $record): string
    {
        $unit = WeightUnit::from($record['parcel_weight_unit']);

        return sprintf(
            '%s %s',
            $this->formatNumber($record['parcel_weight']),
            $unit->getSymbol()
        );
    }

    /**
     * @param float|numeric-string $number
     */
    private function formatNumber($number): string
    {
        return $this->locale->formatNumber($number);
    }

    private function getPickupOrderStatus(array $record, ShipmentType $shipmentType): string
    {
        if (!in_array($shipmentType, [ShipmentType::AddressToPoint(), ShipmentType::AddressToAddress()], true)) {
            return '--';
        }

        if ($record['pickup_order_id']) {
            return $this->translator->trans('Yes', [], 'Admin.Global');
        }

        return $this->translator->trans('No', [], 'Admin.Global');
    }

    private function formatStatus(string $status): string
    {
        // initial shipment status
        if ('CREATED' === $status) {
            return $this->translator->trans('Created', [], 'Modules.Inpostinternational.Tracking');
        }

        return (new TrackingEvent($status))->trans($this->translator);
    }
}
