<?php

declare(strict_types=1);

namespace Drupal\flowdrop_trigger\Form;

use Drupal\Core\Form\FormStateInterface;

/**
 * Cron events settings form for FlowDrop Trigger module.
 *
 * Allows configuration of cron-related trigger settings including:
 * - Enable/disable cron triggers
 * - Which cron event types to allow
 * - Minimum interval between cron trigger executions
 * - Maximum workflows to trigger per cron run
 * - Logging options.
 *
 * @see \Drupal\flowdrop_trigger\Form\TriggerSettingsCategoryFormBase
 *
 * @internal This class is not part of the public API and may change without notice.
 */
final class TriggerSettingsCronForm extends TriggerSettingsCategoryFormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId(): string {
    return "flowdrop_trigger_settings_cron";
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames(): array {
    return ["flowdrop_trigger.settings.cron"];
  }

  /**
   * {@inheritdoc}
   */
  protected function getCategoryId(): string {
    return "cron";
  }

  /**
   * {@inheritdoc}
   */
  protected function getCategoryLabel(): string {
    return "Cron";
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state): array {
    $config = $this->config("flowdrop_trigger.settings.cron");

    $form["description"] = [
      "#type" => "markup",
      "#markup" => "<p>" . $this->t("Configure cron-based workflow triggers. These settings control how workflows are executed when Drupal's cron runs.") . "</p>",
    ];

    // =========================================================================
    // Master Toggle.
    // =========================================================================
    $form["enabled"] = $this->buildEnabledField($form_state);

    // =========================================================================
    // Event Types Section.
    // =========================================================================
    $form["event_types_wrapper"] = $this->buildEventTypesField($form_state);

    // =========================================================================
    // Execution Control Section.
    // =========================================================================
    $form["execution"] = [
      "#type" => "details",
      "#title" => $this->t("Execution Control"),
      "#open" => TRUE,
      "#tree" => TRUE,
    ];

    $form["execution"]["min_interval"] = [
      "#type" => "number",
      "#title" => $this->t("Minimum interval between executions"),
      "#description" => $this->t("Minimum number of seconds that must pass between cron trigger executions. Set to 0 to allow every cron run to trigger workflows. This is useful if your cron runs very frequently (e.g., every minute)."),
      "#default_value" => $config->get("min_interval") ?? 0,
      "#min" => 0,
      "#max" => 86400,
      "#field_suffix" => $this->t("seconds"),
    ];

    $form["execution"]["max_workflows_per_run"] = [
      "#type" => "number",
      "#title" => $this->t("Maximum workflows per cron run"),
      "#description" => $this->t("Maximum number of workflows to trigger during a single cron run. Set to 0 for unlimited. This prevents cron from being overwhelmed if many workflows are configured."),
      "#default_value" => $config->get("max_workflows_per_run") ?? 0,
      "#min" => 0,
      "#max" => 1000,
    ];

    // =========================================================================
    // Logging Options.
    // =========================================================================
    $form["logging"] = [
      "#type" => "details",
      "#title" => $this->t("Logging"),
      "#open" => FALSE,
      "#tree" => TRUE,
    ];

    $form["logging"]["log_cron_triggers"] = [
      "#type" => "checkbox",
      "#title" => $this->t("Log cron trigger events"),
      "#description" => $this->t("When enabled, detailed information about cron trigger executions is logged. Useful for debugging but may generate significant log entries if cron runs frequently."),
      "#default_value" => $config->get("log_cron_triggers") ?? FALSE,
    ];

    // =========================================================================
    // Use Cases Information.
    // =========================================================================
    $form["use_cases"] = [
      "#type" => "details",
      "#title" => $this->t("Common Use Cases"),
      "#open" => FALSE,
    ];

    $form["use_cases"]["info"] = [
      "#type" => "markup",
      "#markup" => "<div class=\"messages messages--info\">" .
      "<p><strong>" . $this->t("Cron triggers are ideal for:") . "</strong></p>" .
      "<ul>" .
      "<li>" . $this->t("Periodic data synchronization with external services") . "</li>" .
      "<li>" . $this->t("Scheduled content publishing or unpublishing") . "</li>" .
      "<li>" . $this->t("Automated cleanup and maintenance tasks") . "</li>" .
      "<li>" . $this->t("Report generation at regular intervals") . "</li>" .
      "<li>" . $this->t("Cache warming and optimization tasks") . "</li>" .
      "<li>" . $this->t("Scheduled email digests and notifications") . "</li>" .
      "</ul>" .
      "<p><em>" . $this->t("Note: Cron triggers fire when Drupal's cron runs, so the frequency depends on your cron configuration.") . "</em></p>" .
      "</div>",
    ];

    // =========================================================================
    // Performance Considerations.
    // =========================================================================
    $form["performance"] = [
      "#type" => "details",
      "#title" => $this->t("Performance Considerations"),
      "#open" => FALSE,
    ];

    $form["performance"]["notice"] = [
      "#type" => "markup",
      "#markup" => "<div class=\"messages messages--warning\">" .
      "<p><strong>" . $this->t("Important:") . "</strong></p>" .
      "<ul>" .
      "<li>" . $this->t("Cron-triggered workflows run asynchronously by default to prevent blocking cron execution.") . "</li>" .
      "<li>" . $this->t("If cron runs frequently, use the 'Minimum interval' setting to prevent excessive workflow executions.") . "</li>" .
      "<li>" . $this->t("Long-running workflows should be configured to use the asynchronous orchestrator.") . "</li>" .
      "<li>" . $this->t("Monitor your queue workers if many cron-triggered workflows are queued.") . "</li>" .
      "</ul></div>",
    ];

    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    $config = $this->config("flowdrop_trigger.settings.cron");

    // Master toggle.
    $config->set("enabled", (bool) $form_state->getValue("enabled"));

    // Process event types from nested structure.
    $eventTypesWrapper = $form_state->getValue("event_types_wrapper", []);
    $allowedEventTypes = $this->filterCheckboxValues(
      $eventTypesWrapper["allowed_event_types"] ?? []
    );
    $config->set("allowed_event_types", $allowedEventTypes);

    // Process execution settings from nested structure.
    $execution = $form_state->getValue("execution", []);
    $config->set("min_interval", (int) ($execution["min_interval"] ?? 0));
    $config->set("max_workflows_per_run", (int) ($execution["max_workflows_per_run"] ?? 0));

    // Process logging settings from nested structure.
    $logging = $form_state->getValue("logging", []);
    $config->set("log_cron_triggers", (bool) ($logging["log_cron_triggers"] ?? FALSE));

    $config->save();

    parent::submitForm($form, $form_state);
  }

}
