<?php
/**
 * SimplyIN Payment Module
 *
 * InPost shipping module integrator for setting pickup point extension attributes.
 */
declare(strict_types=1);

namespace Simplyin\Payment\Model\Integrator;

use Magento\Framework\Module\Manager as ModuleManager;
use Magento\Quote\Api\Data\CartInterface;
use Psr\Log\LoggerInterface;
use Simplyin\Payment\Api\IntegratorInterface;

/**
 * Class InpostIntegrator
 *
 * Handles integration with the Smartmage/Inpost shipping module.
 * Sets the inpost_locker_id extension attribute on quotes when
 * a user selects an InPost parcel locker.
 *
 * @see Requirements 2.1, 2.2, 2.3
 */
class InpostIntegrator implements IntegratorInterface
{
    /**
     * Module name for Smartmage InPost
     */
    private const MODULE_NAME = 'Smartmage_Inpost';

    /**
     * Extension attribute name for InPost locker ID
     */
    private const EXTENSION_ATTRIBUTE_NAME = 'inpost_locker_id';

    /**
     * @var ModuleManager
     */
    private ModuleManager $moduleManager;

    /**
     * @var LoggerInterface
     */
    private LoggerInterface $logger;

    /**
     * Constructor
     *
     * @param ModuleManager $moduleManager
     * @param LoggerInterface $logger
     */
    public function __construct(
        ModuleManager $moduleManager,
        LoggerInterface $logger
    ) {
        $this->moduleManager = $moduleManager;
        $this->logger = $logger;
    }

    /**
     * Check if the Smartmage/Inpost module is available and enabled
     *
     * @return bool True if the Smartmage_Inpost module is installed and active
     */
    public function isAvailable(): bool
    {
        return $this->moduleManager->isEnabled(self::MODULE_NAME);
    }

    /**
     * Set the InPost locker ID on the quote
     *
     * Extracts the lockerId from the parcel locker data and sets it as
     * the inpost_locker_id extension attribute on the quote.
     *
     * @param CartInterface $quote The quote to set pickup point data on
     * @param array $data Pickup point data containing:
     *                    - lockerId: string - The InPost locker ID
     * @return bool True if the locker ID was successfully set
     */
    public function setPickupPoint(CartInterface $quote, array $data): bool
    {
        if (!$this->isAvailable()) {
            $this->logger->info(
                'InpostIntegrator: Smartmage_Inpost module is not enabled, skipping integration'
            );
            return false;
        }

        if (!isset($data['lockerId']) || empty($data['lockerId'])) {
            $this->logger->warning(
                'InpostIntegrator: Missing or empty lockerId in pickup point data'
            );
            return false;
        }

        $lockerId = (string) $data['lockerId'];

        try {
            $extensionAttributes = $quote->getExtensionAttributes();
            
            if ($extensionAttributes === null) {
                $this->logger->warning(
                    'InpostIntegrator: Unable to get extension attributes from quote'
                );
                return false;
            }

            // Set the inpost_locker_id extension attribute
            $extensionAttributes->setInpostLockerId($lockerId);
            $quote->setExtensionAttributes($extensionAttributes);

            $this->logger->info(
                sprintf(
                    'InpostIntegrator: Successfully set inpost_locker_id "%s" on quote %s',
                    $lockerId,
                    $quote->getId() ?? 'new'
                )
            );

            return true;
        } catch (\Exception $e) {
            $this->logger->error(
                sprintf(
                    'InpostIntegrator: Failed to set inpost_locker_id: %s',
                    $e->getMessage()
                )
            );
            return false;
        }
    }

    /**
     * Get the provider names this integrator handles
     *
     * @return array List containing 'inpost'
     */
    public function getProviderNames(): array
    {
        return ['inpost'];
    }
}
