<?php

declare(strict_types=1);

namespace Drupal\Tests\netforum\Kernel;

use Drupal\KernelTests\KernelTestBase;
use Drupal\netforum\SoapWsdlCacheType;
use Drupal\netforum\xWeb\Generated\StructType\GetTimeZones;
use Drupal\netforum\xWeb\Generated\StructType\GetTimeZonesResponse;
use Drupal\netforum\xWeb\Generated\StructType\TestConnection;
use Drupal\netforum\xWeb\Generated\StructType\TestConnectionResponse;
use Drupal\Tests\netforum\Traits\NetForumConfigTrait;
use Drupal\Tests\netforum\Utilities\RandomText;
use Drupal\Tests\netforum\xWeb\NetForumXmlSettings;
use Drupal\Tests\netforum\xWeb\SoapServerManager;

/**
 * Test the NetForumXmlService.
 *
 * @group netforum
 */
final class NetForumXmlServiceTest extends KernelTestBase {

  use NetForumConfigTrait;

  protected static $modules = ['system', 'netforum'];

  private SoapServerManager $soapServerManager;

  private string $xWebUsername;

  private string $xWebPassword;

  /**
   * Test getting a NetForumXML client and using it to call xWeb SOAP functions.
   *
   * @throws \Exception
   */
  public function testClient(): void {
    $this->resetConfiguration();

    $this->getEditableConfiguration()
      ->set('xweb_endpoint', 'http://127.0.0.1:' . $this->soapServerManager->getSoapServerPort())
      ->set('xweb_username', $this->xWebUsername)
      ->set('xweb_password', $this->xWebPassword)
      ->set('wsdl_cache', SoapWsdlCacheType::None->value)
      ->save();

    /** @var \Drupal\netforum\NetForumXmlService $netforumXmlService */
    $netforumXmlService = $this->container->get('netforum.xweb.netforum_xml');

    $nfClient = $netforumXmlService->getClient();
    $testConnectionResponse = $nfClient->TestConnection(new TestConnection());
    $this->assertinstanceof(TestConnectionResponse::class, $testConnectionResponse);
    $this->assertSame('Success', $testConnectionResponse->getTestConnectionResult());

    $getTimeZonesResponse = $nfClient->GetTimeZones(new GetTimeZones());
    $this->assertinstanceof(GetTimeZonesResponse::class, $getTimeZonesResponse);
    $this->assertNotNull($getTimeZonesResponse->getGetTimeZonesResult());

    $this->assertSame($nfClient, $netforumXmlService->getClient());
  }

  /**
   * Set up the test.
   *
   * @throws \Random\RandomException
   */
  protected function setUp(): void {
    parent::setUp();

    $this->installConfig(['netforum']);

    $this->configureNetForumConfig($this->container->get('config.factory'), $this->container->get('config.storage'));

    $this->xWebUsername = RandomText::getRandomText(4);
    $this->xWebPassword = RandomText::getRandomText(8);
    $nfSettings = new NetForumXmlSettings($this->xWebUsername, $this->xWebPassword);
    $this->soapServerManager = new SoapServerManager($nfSettings);
    $this->soapServerManager->startSoapServer();
  }

  protected function tearDown(): void {
    $this->soapServerManager->stopSoapServer();

    parent::tearDown();
  }

}
