<?php

namespace Drupal\user_provisioning\Helpers;

use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Database\Connection;
use Drupal\user_provisioning\moUserProvisioningConstants;
use Psr\Log\LoggerInterface;

/**
 * Handles audit log persistence for user provisioning events.
 */
class moUserProvisioningAudits {
  /**
   * Database connection used for audit writes.
   *
   * @var \Drupal\Core\Database\Connection
   */
  private Connection $connection;
  /**
   * Logger channel for audit write failures.
   *
   * @var \Psr\Log\LoggerInterface
   */
  private LoggerInterface $logger;
  /**
   * User provisioning module configuration.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  private ImmutableConfig $config;

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

  /**
   * Returns an array containing the fields of the Audits and Logs table.
   *
   * @return string[]
   *   The database field names used for audit inserts.
   */
  public function getFields(): array {
    return ['uid', 'name', 'created', 'operation', 'status'];
  }

  /**
   * Adds the audit entry in the database.
   *
   * @param array $values
   *   The row values mapped to audit table fields.
   *
   * @return \Drupal\Core\Database\StatementInterface|int|string|null
   *   Insert result on success, or NULL on failure.
   */
  public function addAudit(array $values) {
    try {
      return $this->connection->insert(moUserProvisioningConstants::AUDIT_LOG_TABLE)
        ->fields($this->getFields(), $values)
        ->execute();
    }
    catch (\Exception $exception) {
      $this->logger->error($exception->getMessage());

      // @todo handle this case by throwing an exception.
      return NULL;
    }
  }

}
