<?php

declare(strict_types=1);

namespace Drupal\farm_ui_views\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Checks access for displaying Views of assets that reference organizations.
 */
class FarmOrganizationAssetViewsAccessCheck implements AccessInterface {

  public function __construct(
    protected EntityTypeManagerInterface $entityTypeManager,
  ) {}

  /**
   * A custom access check.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match.
   */
  public function access(RouteMatchInterface $route_match) {

    // Get the "organization" parameter and attempt to load the organization.
    // If the organization cannot be loaded, allow access so that views
    // contextual filter validation returns a 404.
    $organization_id = $route_match->getParameter('organization');
    /** @var \Drupal\organization\Entity\OrganizationInterface|null $organization */
    $organization = $this->entityTypeManager->getStorage('organization')->load($organization_id);
    if (is_null($organization)) {
      return AccessResult::allowed();
    }

    // Get the "asset_type" parameter. If it is empty or "all", allow access so
    // that Views can handle it.
    $asset_type = $route_match->getParameter('asset_type');
    if (empty($asset_type) || $asset_type == 'all') {
      return AccessResult::allowed();
    }

    // Build a count query for asset of this type.
    // Only include assets that reference the organization.
    $query = $this->entityTypeManager->getStorage('asset')->getAggregateQuery()
      ->accessCheck(TRUE)
      ->condition('type', $asset_type)
      ->condition('farm.entity.id', $organization_id)
      ->count();

    // Determine access based on the asset count.
    $count = $query->execute();
    $access = AccessResult::allowedIf($count > 0);

    // Invalidate the access result when assets of this bundle are changed.
    $access->addCacheTags(["asset_list:$asset_type"]);
    return $access;
  }

}
