<?php

declare(strict_types=1);

namespace Drupal\flowdrop_trigger\Hook;

use Drupal\Core\Hook\Attribute\Hook;
use Drupal\Core\State\StateInterface;
use Drupal\flowdrop_trigger\Service\TriggerManagerInterface;

/**
 * Implements cron hooks for FlowDrop ecosystem.
 *
 * Fires cron-based workflow triggers when Drupal's cron runs.
 * This allows workflows to be scheduled for periodic execution.
 *
 * @internal This class is not part of the public API and may change without notice.
 */
class CronHooks {

  /**
   * Constructs a new CronHooks object.
   *
   * @param \Drupal\flowdrop_trigger\Service\TriggerManagerInterface $triggerManager
   *   The trigger manager service.
   * @param \Drupal\Core\State\StateInterface $state
   *   The state service for tracking last cron run.
   */
  public function __construct(
    protected readonly TriggerManagerInterface $triggerManager,
    protected readonly StateInterface $state,
  ) {}

  /**
   * Implements hook_cron().
   *
   * Fires the cron.run event to trigger any workflows configured
   * for cron-based execution.
   */
  #[Hook('cron')]
  public function cron(): void {
    // Get the last cron run timestamp for context.
    $lastRun = $this->state->get("flowdrop_trigger.last_cron_run", 0);

    // Build context with cron-specific information.
    $context = [
      "last_run" => $lastRun,
      "cron_key" => NULL,
    ];

    // Process the cron event.
    $this->triggerManager->processCronEvent("cron.run", $context);

    // Update the global last cron run timestamp.
    $this->state->set("flowdrop_trigger.last_cron_run", time());
  }

}
