<?php
/**
 * Copyright 2020 Adobe
 * All Rights Reserved.
 *
 * NOTICE: Adobe permits you to use, modify, and distribute this file in
 * accordance with the terms of the Adobe license agreement accompanying
 * it.
 */
namespace Sut\Infrastructure\GraphQl;

use RuntimeException;
use Sut\Domain\Cmd\CmdServiceInterface;
use Sut\Domain\Issue\IssueFactory;

class GraphQl
{
    /**
     * @var CmdServiceInterface
     */
    private $cmdService;

    /**
     * @var IssueFactory
     */
    private $issueFactory;

    /**
     * @param CmdServiceInterface $cmdService
     * @param IssueFactory $issueFactory
     */
    public function __construct(CmdServiceInterface $cmdService, IssueFactory $issueFactory)
    {
        $this->cmdService = $cmdService;
        $this->issueFactory = $issueFactory;
    }

    /**
     * @param string $oldSchemaUrl
     * @param string $newSchemaUrl
     * @param string $schemaVerificationPath
     * @return array
     * @throws RuntimeException
     */
    public function getSchemaDiff(string $oldSchemaUrl, string $newSchemaUrl, string $schemaVerificationPath): array
    {
        $commandExecution = $this->cmdService->execCommand(
            "node $schemaVerificationPath $oldSchemaUrl $newSchemaUrl 2>&1",
        );

        $output = $commandExecution->getOutput();

        if ($commandExecution->getExitCode() !== 0) {
            throw new RuntimeException(implode("\n", $output) ?? '');
        }

        $schemaDiff = [];
        if (!isset($output[0])) {
            return [];
        }

        $result = json_decode($output[0]);
        if (!is_array($result)) {
            return [];
        }

        foreach ($result as $issue) {
            $schemaDiff[] = $this->issueFactory->createIssueByType(
                $issue->type,
                $issue->description
            );
        }

        return $schemaDiff;
    }
}
