<?php

namespace Drupal\user_provisioning\Helpers;

use Drupal\Core\Config\ImmutableConfig;
use Psr\Log\LoggerInterface;

/**
 * Provides structured logging helpers for user provisioning.
 */
class moUserProvisioningLogger {
  /**
   * Drupal logger channel instance.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected LoggerInterface $logger;
  /**
   * User provisioning module configuration.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  private ImmutableConfig $config;

  /**
   * Constructs the user provisioning logger helper.
   */
  public function __construct() {
    $this->logger = \Drupal::logger('user_provisioning');
    $this->config = \Drupal::config('user_provisioning.settings');
  }

  /**
   * Adds a formatted log entry with rendered content.
   *
   * @param array $content
   *   The content that will be added to the log.
   * @param int $line
   *   The line on which the log is initiated __LINE__.
   * @param string $function
   *   The function in which the log is initiated __FUNCTION__.
   * @param string $file
   *   The file in which the log is initiated __FILE__.
   * @param string $description
   *   Additional details related to the log output.
   *
   * @return void
   */
  public function addFormattedLog($content, int $line, string $function, string $file, string $description = '') {
    if ($this->isLoggingEnabled()) {
      $this->logger->info(basename($file) . '-' . $function . '()- ' . $line . ': ' . $description . '<pre><code>' . print_r($content, TRUE) . '</code></pre>');
    }
  }

  /**
   * Adds a plain-text log entry.
   *
   * @param string $content
   *   The content that will be added to the log.
   * @param int $line
   *   The line on which the log is initiated __LINE__.
   * @param string $function
   *   The function in which the log is initiated __FUNCTION__.
   * @param string $file
   *   The file in which the log is initiated __FILE__.
   *
   * @return void
   */
  public function addLog(string $content, int $line, string $function, string $file) {
    if ($this->isLoggingEnabled()) {
      $this->logger->info(basename($file) . '-' . $function . '()- ' . $line . ': ' . $content);
    }
  }

  /**
   * Check if the option to add logs is enabled.
   *
   * @return bool
   *   TRUE when logging is enabled; otherwise FALSE.
   */
  private function isLoggingEnabled(): bool {
    if ($this->config->get('mo_user_provisioning_enable_loggers')) {
      return TRUE;
    }
    return FALSE;
  }

}
