<?php

namespace App\Command;

use App\Controller\ShopwareController;
use App\Repository\OrdersRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Vin\ShopwareSdk\Client\AdminAuthenticator;
use Vin\ShopwareSdk\Client\GrantType\ClientCredentialsGrantType;
use Vin\ShopwareSdk\Data\Context;
use Vin\ShopwareSdk\Data\Criteria;
use Vin\ShopwareSdk\Data\Entity\Order\OrderDefinition;
use Vin\ShopwareSdk\Data\Entity\Product\ProductDefinition;
use Vin\ShopwareSdk\Data\Filter\EqualsFilter;
use Vin\ShopwareSdk\Factory\RepositoryFactory;


#[AsCommand(
    name: 'sw:get-orders',
    description: 'Holt alle offenen Bestellungen von SW ab',
)]
class SwGetOrdersCommand extends Command
{
    private $ordersRepository;
    private $client;
    private $logger;


  public function __construct(OrdersRepository $ordersRepository, HttpClientInterface $client,   LoggerInterface $logger )
    {
        $this->ordersRepository = $ordersRepository;
        $this->client = $client;
        $this->logger = $logger;
        parent::__construct();
    }

    protected function configure(): void
    {
        $this
            ->addArgument('arg1', InputArgument::OPTIONAL, 'Argument description')
            ->addOption('option1', null, InputOption::VALUE_NONE, 'Option description')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        $arg1 = $input->getArgument('arg1');

        if ($arg1) {
            $io->note(sprintf('You passed an argument: %s', $arg1));
        }

        if ($input->getOption('option1')) {
            // ...
        }

        //offene Bestellungen aus Datenbank holen
        $orders = $this->getOrders();

        if(!$orders) {
            $io->error('Keine Bestellungen gefunden');
            return Command::FAILURE;
        }

        //Bestelldetails aus SW holen
        $this->getOrdersFromSW($orders);


        $io->success('Done!');
        return Command::SUCCESS;
    }

    private function getOrders():array
    {
      return $this->ordersRepository->findAll();
    }

    private function shopwareAuth(){

      try{
        $grantType = new ClientCredentialsGrantType($_ENV['SHOPWARE_API_ID'], $_ENV['SHOPWARE_API_KEY']);
        $adminClient = new AdminAuthenticator($grantType, $_ENV['SHOPWARE_API_URL']);
        return $adminClient->fetchAccessToken();
      }catch (\Exception $e){
        $this->logger->error($e->getMessage());
      }


    }

  /**
   * @throws TransportExceptionInterface
   * @throws ServerExceptionInterface
   * @throws RedirectionExceptionInterface
   * @throws DecodingExceptionInterface
   * @throws ClientExceptionInterface
   * @throws \Exception
   */
  private function getOrdersFromSW(array $ordersArr):void
    {

      $context = new Context($_ENV['SHOPWARE_API_URL'], $this->shopwareAuth());

      // Create the repository for the entity
      $orderRepository = RepositoryFactory::create(OrderDefinition::ENTITY_NAME);

      // Create the criteria
      $criteria = new Criteria();
      $criteria->addFilter(new EqualsFilter('orderNumber', '9f002cc7de704a6ab31e1b410547cb97'));

      $criteria->addAssociation('order.orderDetails.product');

      // Using this criteria and the context object that you create from authentication step, you can retrieving the result
      $orders = $orderRepository->search($criteria, $context);



        var_dump($orders);



    }

}
