<?php

declare(strict_types=1);

namespace Drupal\flowdrop_trigger\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Url;
use Drupal\flowdrop_trigger\Entity\FlowDropTriggerConfig;
use Drupal\flowdrop_trigger\FlowDropTriggerConfigInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

/**
 * Controller for viewing FlowDrop Trigger Configuration entities.
 *
 * For config entities, the canonical route redirects to the edit form
 * since config entities don't have view modes.
 */
class TriggerConfigViewController extends ControllerBase {

  /**
   * View a trigger configuration entity.
   *
   * Redirects to the edit form since config entities don't have view modes.
   *
   * @param \Drupal\flowdrop_trigger\FlowDropTriggerConfigInterface $flowdrop_trigger_config
   *   The trigger configuration entity.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   Redirect response to the edit form.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
   *   If entity is not found.
   */
  public function view(FlowDropTriggerConfigInterface $flowdrop_trigger_config) {
    // For config entities, redirect to edit form using the entity's toUrl
    // method.
    return new RedirectResponse($flowdrop_trigger_config->toUrl("edit-form")->toString());
  }

  /**
   * Configure trigger for a workflow and node.
   *
   * Accepts workflow ID and node ID as query parameters, then redirects to
   * the edit form if the trigger config exists, or the add form if it doesn't.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object containing workflow and node query parameters.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   Redirect response to either edit or add form.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
   *   If required parameters are missing.
   */
  public function configure(Request $request): RedirectResponse {
    $workflowId = $request->query->get("workflow");
    $nodeId = $request->query->get("node");

    if (empty($workflowId)) {
      throw new BadRequestHttpException("workflow parameter is required");
    }

    if (empty($nodeId)) {
      throw new BadRequestHttpException("node parameter is required");
    }

    // Generate the entity ID from workflow and node IDs.
    $entityId = FlowDropTriggerConfig::generateId((string) $workflowId, (string) $nodeId);

    // Check if entity exists.
    $storage = $this->entityTypeManager()->getStorage("flowdrop_trigger_config");
    /** @var \Drupal\flowdrop_trigger\FlowDropTriggerConfigInterface|null $entity */
    $entity = $storage->load($entityId);

    if ($entity !== NULL) {
      // Entity exists, redirect to edit form.
      return new RedirectResponse($entity->toUrl("edit-form")->toString());
    }

    // Entity doesn't exist, redirect to add form with query parameters.
    $queryParams = [
      "workflow" => $workflowId,
      "node" => $nodeId,
    ];

    // Pass through label parameter if provided.
    $labelParam = $request->query->get("label");
    if (!empty($labelParam)) {
      $queryParams["label"] = $labelParam;
    }

    // Pass through category parameter if provided (for filtering event types).
    $categoryParam = $request->query->get("category");
    if (!empty($categoryParam)) {
      $queryParams["category"] = $categoryParam;
    }

    // Use the entity type's add-form link template.
    $url = Url::fromRoute("entity.flowdrop_trigger_config.add_form", [], [
      "query" => $queryParams,
    ]);

    return new RedirectResponse($url->toString());
  }

}
