<?php

/**
 * @file
 * Provides hooks for the sample content module.
 */

declare(strict_types=1);

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Access\AccessResultReasonInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\node\NodeInterface;
use Drupal\samples\Access\NodeAccess;
use Drupal\samples\EntityDecorator\Node;

/**
 * Implements hook_node_access_records().
 */
function samples_node_access_records(NodeInterface $node): ?array {
  $samples_node_access = \Drupal::service('samples.node_access');
  assert($samples_node_access instanceof NodeAccess);
  return $samples_node_access->getAccessRecords($node);
}

/**
 * Implements hook_node_grants().
 */
function samples_node_grants(AccountInterface $account, $op): array {
  $samples_node_access = \Drupal::service('samples.node_access');
  assert($samples_node_access instanceof NodeAccess);
  return $samples_node_access->getGrants($account, $op);
}

/**
 * Implements hook_entity_base_field_info().
 */
function samples_entity_base_field_info(EntityTypeInterface $entity_type): array {
  $fields = [];
  if ($entity_type->id() === 'node') {
    $fields['samples_status'] = Node::getSamplesStatusBaseFieldDefinition();
  }
  return $fields;
}

/**
 * Implements hook_entity_field_access().
 */
function samples_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account): AccessResult {
  // Determines if this hook applies to the given field.
  $concerned = $operation === 'edit' && $field_definition->getName() === 'samples_status' && $field_definition->getTargetEntityTypeId() === 'node';
  $permission = 'administer content samples';
  // If this module is concerned with the field and the user does not have
  // permission to edit it, then forbid access to the field. Otherwise, the
  // result will be neutral so that access will be determined by the entity
  // access handler or other field access hooks.
  $concerned_and_missing_permission = $concerned && !$account->hasPermission($permission);
  $access_result = AccessResult::forbiddenIf($concerned_and_missing_permission)->addCacheContexts(['user.permissions']);
  if ($access_result->isForbidden() && $access_result instanceof AccessResultReasonInterface) {
    $access_result->setReason("The '$permission' permission is required.");
  }
  return $access_result;
}
