<?php

declare(strict_types=1);

namespace Drupal\flowdrop_workflow\Controller;

use Drupal\flowdrop_workflow\Entity\FlowDropWorkflow;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Render\HtmlResponse;
use Drupal\Core\Url;
use Drupal\flowdrop_node_type\Service\NodeMetadataResolver;
use Drupal\flowdrop_ui_components\Helper\UiConfigBuilder;
use Drupal\flowdrop_ui_components\Render\BarePageRenderer;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Returns responses for flowdrop routes.
 *
 * @internal This class is not part of the public API and may change without notice.
 */
final class WorkflowController extends ControllerBase {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The FlowDrop endpoint config service.
   *
   * @var \Drupal\flowdrop_ui_components\Service\FlowDropEndpointConfigService
   */
  protected $endpointConfigService;

  /**
   * The navbar menu builder.
   *
   * @var \Drupal\flowdrop_workflow\Service\NavbarMenuBuilder
   */
  protected $navbarMenuBuilder;

  /**
   * The bare full-page renderer.
   *
   * @var \Drupal\flowdrop_ui_components\Render\BarePageRenderer
   */
  protected BarePageRenderer $barePageRenderer;

  /**
   * The node metadata resolver.
   *
   * @var \Drupal\flowdrop_node_type\Service\NodeMetadataResolver
   */
  protected NodeMetadataResolver $metadataResolver;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): static {
    $instance = new static();
    $instance->entityTypeManager = $container->get('entity_type.manager');
    $instance->endpointConfigService = $container->get('flowdrop_ui_components.endpoint_config');
    $instance->navbarMenuBuilder = $container->get('flowdrop_workflow.navbar_menu_builder');
    $instance->barePageRenderer = $container->get('flowdrop_ui_components.bare_page_renderer');
    $instance->metadataResolver = $container->get('flowdrop_node_type.metadata_resolver');
    return $instance;
  }

  /**
   * Opens a specific workflow entity in the FlowDrop editor.
   *
   * Uses the flowdrop_ui_components:editor SDC component to render the
   * workflow editor interface.
   *
   * @param \Drupal\flowdrop_workflow\Entity\FlowDropWorkflow $flowdrop_workflow
   *   The flowdrop workflow entity to open.
   *
   * @return \Drupal\Core\Render\HtmlResponse
   *   A bare, theme-free HTML page hosting the editor.
   */
  public function openWorkflowEntity(FlowDropWorkflow $flowdrop_workflow): HtmlResponse {
    // Prepare workflow data for the frontend.
    $workflow_data = [
      'id' => $flowdrop_workflow->id(),
      'label' => $flowdrop_workflow->label(),
      'description' => $flowdrop_workflow->getDescription(),
      // Enrich on read: stored nodes carry only the slim node-type anchor, so
      // re-inject the derived metadata (ports, configSchema, visual type) the
      // editor needs to render. Mirrors the API/form/export read paths.
      'nodes' => $this->metadataResolver->enrichNodes($flowdrop_workflow->getNodes()),
      'edges' => $flowdrop_workflow->getEdges(),
      'metadata' => $flowdrop_workflow->getMetadata(),
      'created' => $flowdrop_workflow->getCreated(),
      'changed' => $flowdrop_workflow->getChanged(),
    ];

    // Build the API base URL for endpoint configuration.
    $url_options = [
      'absolute' => TRUE,
      'language' => $this->languageManager()->getCurrentLanguage(),
    ];
    $site_url = Url::fromRoute('<front>', [], $url_options)->toString();

    // Generate endpoint configuration.
    $endpoint_config = $this->endpointConfigService->generateAbsoluteEndpointConfig($site_url);

    // Build navbar items from this page's local tasks (Playground and any
    // contrib-provided tabs) and local actions (Back and any contrib links).
    $navbar_tasks = $this->navbarMenuBuilder->localTasks('flowdrop.workflow.editor');
    $navbar_actions = $this->navbarMenuBuilder->localActions('flowdrop.workflow.editor');

    // Global UI configuration shared with the playground SDC. Two config keys
    // (default_settings + exposed_categories) are combined into the single
    // JSON shape that the SDC's data-ui-config attribute expects.
    $ui_config = UiConfigBuilder::fromConfig(
      $this->config('flowdrop_ui_components.settings'),
    );

    // Render using the SDC editor component.
    $content = [
      '#type' => 'component',
      '#component' => 'flowdrop_ui_components:editor',
      '#props' => [
        'workflow' => $workflow_data,
        'endpoint_config' => $endpoint_config,
        'editor_id' => 'flowdrop-editor-' . $flowdrop_workflow->id(),
        'height' => '100%',
        'width' => '100%',
        'show_navbar' => TRUE,
        'navbar_title' => $flowdrop_workflow->label(),
        'navbar_tasks' => $navbar_tasks,
        'navbar_actions' => $navbar_actions,
        'show_save_button' => TRUE,
        'enable_keyboard_shortcuts' => TRUE,
        'ui_config' => $ui_config,
      ],
      '#attached' => [
        'library' => [
          'flowdrop_workflow/editor',
        ],
      ],
      // Navbar tasks vary by route and the user's access to each tab.
      '#cache' => [
        'contexts' => ['route', 'user.permissions'],
      ],
    ];

    return $this->barePageRenderer->render($content, (string) $flowdrop_workflow->label());
  }

}
