<?php

declare(strict_types=1);

namespace Drupal\flowdrop_workflow\Controller;

use Drupal\flowdrop_workflow\Entity\FlowDropWorkflow;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
   * Returns responses for flowdrop routes.
   */
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;

  /**
   * {@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');
    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 array
   *   The render array for the editor page with workflow data.
   */
  public function openWorkflowEntity(FlowDropWorkflow $flowdrop_workflow): array {
    // Prepare workflow data for the frontend.
    $workflow_data = [
      'id' => $flowdrop_workflow->id(),
      'label' => $flowdrop_workflow->label(),
      'description' => $flowdrop_workflow->getDescription(),
      'nodes' => $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(),
    ];
    $base_url = Url::fromRoute('<front>', [], $url_options)->toString() . '/api/flowdrop';

    // Generate endpoint configuration.
    $endpoint_config = $this->endpointConfigService->generateEndpointConfig($base_url);

    // Build the back URL for the navbar.
    $back_url = Url::fromRoute('entity.flowdrop_workflow.collection')->toString();

    // Render using the SDC editor component.
    $build['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(),
        'back_url' => $back_url,
        'show_save_button' => TRUE,
        'show_back_button' => TRUE,
        'enable_keyboard_shortcuts' => TRUE,
      ],
      '#attached' => [
        'library' => [
          'flowdrop_workflow/editor',
        ],
        // Keep drupalSettings for backward compatibility with any code
        // that might still reference them.
        'drupalSettings' => [
          'flowdrop' => [
            'apiBaseUrl' => $base_url,
            'endpointConfig' => $endpoint_config,
            'workflow' => $workflow_data,
          ],
        ],
      ],
    ];

    return $build;
  }

}
