<?php

declare(strict_types=1);

namespace Drupal\sobki_admin\Hook;

use Drupal\Core\Access\AccessManagerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Hook\Attribute\Hook;
use Drupal\Core\Url;
use Drupal\layout_builder\Plugin\SectionStorage\OverridesSectionStorage;
use Drupal\sobki_admin\EventSubscriber\NodeInsertRedirection;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Redirect to Layout Builder form after node insert.
 */
class LayoutBuilderRedirect {

  public function __construct(
    protected AccessManagerInterface $accessManager,
    protected RequestStack $requestStack,
  ) {}

  /**
   * Redirect on the layout builder form if available.
   *
   * Inspired by layout_builder_operation_link module.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity object.
   */
  #[Hook('node_insert')]
  public function redirect(EntityInterface $entity): void {
    $current_request = $this->requestStack->getCurrentRequest();
    if (!$current_request instanceof Request) {
      return;
    }

    $entity_type_id = $entity->getEntityTypeId();

    $route_name = "layout_builder.overrides.{$entity_type_id}.view";
    $route_parameters = [
      $entity_type_id => $entity->id(),
    ];
    $route_options = [];

    // If current user has access to route, then redirect. The
    // access check will only return TRUE if the bundle is Layout Builder
    // enabled, overrides are allowed, and user has necessary permissions.
    if (!$this->accessManager->checkNamedRoute($route_name, $route_parameters)) {
      return;
    }

    // Add entity's language as a route option if layouts are translatable
    // (e.g. the Layout Builder Asymmetric Translation contrib module
    // is installed).
    if ($entity instanceof FieldableEntityInterface
      && $entity->hasField(OverridesSectionStorage::FIELD_NAME)
      && $entity->get(OverridesSectionStorage::FIELD_NAME)->getFieldDefinition()->isTranslatable()
    ) {
      $route_options['language'] = $entity->language();
    }

    $url = Url::fromRoute($route_name, $route_parameters, $route_options);
    $current_request->attributes
      ->set(NodeInsertRedirection::REDIRECT_ATTRIBUTE, $url->toString());
  }

}
