<?php

namespace Drupal\user_provisioning;

use Drupal\Core\Entity\EntityInterface;
use Drupal\user_provisioning\Helpers\moUserProvisioningLogger;
use Psr\Log\LoggerInterface;

/**
 * Handles CRUD operations for provisioning entities.
 */
class moUserProvisioningOperationsHandler {
  /**
   * The entity being provisioned.
   *
   * @var \Drupal\Core\Entity\EntityInterface
   */
  private EntityInterface $entity;

  /**
   * Drupal logger channel for user provisioning.
   *
   * @var \Psr\Log\LoggerInterface
   */
  private LoggerInterface $logger;

  /**
   * Module logger helper for detailed traces.
   *
   * @var \Drupal\user_provisioning\Helpers\moUserProvisioningLogger
   */
  private moUserProvisioningLogger $moLogger;

  /**
   * Constructs an operations handler for a specific entity.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity to be provisioned.
   */
  public function __construct(EntityInterface $entity) {
    $this->entity = $entity;
    $this->logger = \Drupal::logger('user_provisioning');
    $this->moLogger = new moUserProvisioningLogger();
  }

  /**
   * Performs the creation of the supplied entity to the configured application.
   *
   * @throws \Exception
   */
  public function insert() {
    try {
      $operationObject = moUserProvisioningEntityFactory::getEntityHandler($this->entity);
      $this->moLogger->addLog("Object received, calling createResource function.", __LINE__, __FUNCTION__, __FILE__);
      return $operationObject->createResource();
    }
    catch (\Exception $exception) {
      $this->logger->debug($exception->getMessage());
      throw $exception;
    }
  }

  /**
   * Handles entity update operations for provisioning.
   */
  public function update() {
    // @todo Implement update operation handler.
  }

  /**
   * Handles entity deletion operations for provisioning.
   */
  public function delete() {
    // @todo Implement delete operation handler.
  }

  /**
   * Performs the creation of the supplied entity to the configured application.
   *
   * @throws \Exception
   */
  public function deactivate() {
    try {
      $operationObject = moUserProvisioningEntityFactory::getEntityHandler($this->entity);
      $this->moLogger->addLog("Object received, calling deactivateResource function.", __LINE__, __FUNCTION__, __FILE__);
      return $operationObject->deactivateResource();
    }
    catch (\Exception $exception) {
      $this->logger->debug($exception->getMessage());
      throw $exception;
    }
  }

}
