<?php

namespace Drupal\eb_ui\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Access\AccessResultInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\Routing\Route;

/**
 * Access checker for eb_ui definition edit routes.
 *
 * Validates that the user has permission to edit the specified definition,
 * using the entity access control handler to properly enforce Tier 1
 * ownership-based permissions.
 */
class DefinitionEditAccess implements AccessInterface {

  /**
   * Constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manager service.
   */
  public function __construct(
    protected EntityTypeManagerInterface $entityTypeManager,
  ) {}

  /**
   * Checks access for definition edit routes.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The current user account.
   * @param \Symfony\Component\Routing\Route $route
   *   The route being accessed.
   * @param string|null $definition_id
   *   The definition ID from the route parameter.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function access(
    AccountInterface $account,
    Route $route,
    ?string $definition_id = NULL,
  ): AccessResultInterface {
    // If no definition_id, this is a create operation - check create access.
    if (empty($definition_id)) {
      return $this->entityTypeManager
        ->getAccessControlHandler('eb_definition')
        ->createAccess(NULL, $account, [], TRUE);
    }

    // Load the definition entity.
    $definition = $this->entityTypeManager
      ->getStorage('eb_definition')
      ->load($definition_id);

    // If definition doesn't exist, deny access.
    if (!$definition) {
      return AccessResult::forbidden('Definition not found.')
        ->addCacheTags(['eb_definition_list']);
    }

    // Check update access using the entity access handler.
    // This properly enforces Tier 1 ownership-based permissions.
    return $definition->access('update', $account, TRUE);
  }

}
