<?php

namespace PortalPeople\OrderWebhook\Console\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use PortalPeople\OrderWebhook\Model\WebhookSender;

/**
 * Console command to test webhook functionality
 */
class TestWebhookCommand extends Command
{
    const ORDER_ID_ARGUMENT = 'order_id';

    /**
     * @var OrderRepositoryInterface
     */
    private $orderRepository;

    /**
     * @var WebhookSender
     */
    private $webhookSender;

    /**
     * @param OrderRepositoryInterface $orderRepository
     * @param WebhookSender $webhookSender
     * @param string|null $name
     */
    public function __construct(
        OrderRepositoryInterface $orderRepository,
        WebhookSender $webhookSender,
        string $name = null
    ) {
        parent::__construct($name);
        $this->orderRepository = $orderRepository;
        $this->webhookSender = $webhookSender;
    }

    /**
     * Configure command
     */
    protected function configure()
    {
        $this->setName('order:webhook:test')
             ->setDescription('Test webhook functionality with existing order')
             ->addArgument(
                 self::ORDER_ID_ARGUMENT,
                 InputArgument::REQUIRED,
                 'Order ID to test webhook with'
             );
    }

    /**
     * Execute command
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $orderId = $input->getArgument(self::ORDER_ID_ARGUMENT);

        try {
            $order = $this->orderRepository->get($orderId);
            $output->writeln("<info>Testing webhook for order #{$order->getIncrementId()}</info>");

            $result = $this->webhookSender->sendOrderData($order, 'test_webhook');

            if ($result) {
                $output->writeln("<info>Webhook sent successfully!</info>");
                return Command::SUCCESS;
            } else {
                $output->writeln("<error>Webhook failed to send.</error>");
                return Command::FAILURE;
            }

        } catch (\Exception $e) {
            $output->writeln("<error>Error: {$e->getMessage()}</error>");
            return Command::FAILURE;
        }
    }
}
