<?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;

/**
 *
 */
class moUserProvisioningAudits {
  private Connection $connection;
  private LoggerInterface $logger;
  private ImmutableConfig $config;

  /**
   *
   */
  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[]
   */
  public function getFields(): array {
    return ['uid', 'name', 'created', 'operation', 'status'];
  }

  /**
   * Adds the audit entry in the database.
   *
   * @param array $values
   *
   * @return \Drupal\Core\Database\StatementInterface|int|string|null
   */
  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;
    }
  }

}
