<?php

/**
 * @file
 * The social node module alterations.
 */

use Drupal\node\NodeInterface;
use Drupal\social_node\Entity\Node;
use Drupal\social_node\SocialNodeForm;
use Drupal\social_node\NodeViewBuilder;

/**
 * Implements hook_entity_type_alter().
 */
function social_node_entity_type_alter(array &$entity_types) {
  /** @var \Drupal\Core\Entity\EntityTypeInterface[] $entity_types */
  if (isset($entity_types['node'])) {
    $entity_types['node']->setClass(Node::class);
    $entity_types['node']->setViewBuilderClass(NodeViewBuilder::class);

    foreach (['default', 'edit'] as $operation) {
      $entity_types['node']->setFormClass($operation, SocialNodeForm::class);
    }
  }
}

/**
 * Implements hook_social_core_title().
 */
function social_node_social_core_title(): array {
  return [
    'node' => [
      'route_name' => 'node.add',
    ],
  ];
}

/**
 * Implements hook_social_tagging_type().
 */
function social_node_social_tagging_type(): string {
  return 'node';
}

/**
 * Implements hook_node_access_records_alter().
 */
function social_node_node_access_records_alter(array &$grants, NodeInterface $node): void {
  if (
    !$node->hasField('field_content_visibility') ||
    $node->get('field_content_visibility')->isEmpty()
  ) {
    return;
  }

  $visibility = $node->get('field_content_visibility')->getString();

  if ($visibility !== 'public') {
    // Remove "view" realm for all visibility options except "public".
    foreach ($grants as &$grant) {
      if ($grant['realm'] === 'gnode_anonymous') {
        $grant['grant_view'] = 0;
      }
    }
  }
}
