<?php

declare(strict_types=1);

namespace Drupal\flowdrop_session\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Access\AccessResultInterface;
use Drupal\Core\Entity\EntityAccessControlHandler;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\flowdrop\Constants\Permissions as FlowDropPermissions;
use Drupal\flowdrop_session\Constants\Permissions;
use Drupal\flowdrop_session\Entity\FlowDropSessionMessageInterface;

/**
 * Access controller for the Session Message entity.
 *
 * Message access is determined by access to the parent session.
 *
 * @internal This class is not part of the public API and may change without notice.
 */
class FlowDropSessionMessageAccessControlHandler extends EntityAccessControlHandler {

  /**
   * {@inheritdoc}
   */
  protected function checkAccess(EntityInterface $entity, mixed $operation, AccountInterface $account): AccessResultInterface {
    $operation = (string) $operation;
    if (!$entity instanceof FlowDropSessionMessageInterface) {
      return AccessResult::neutral();
    }

    // Global super-admin bypass.
    if ($account->hasPermission(FlowDropPermissions::ADMINISTER_FLOWDROP)) {
      return AccessResult::allowed()->cachePerPermissions();
    }

    // Entity type admin bypass.
    if ($account->hasPermission(Permissions::ADMINISTER)) {
      return AccessResult::allowed()->cachePerPermissions();
    }

    // Message access is based on session access.
    $session = $entity->getSession();
    if ($session === NULL) {
      return AccessResult::forbidden('Parent session not found.');
    }

    switch ($operation) {
      case 'view':
        if ($account->hasPermission(Permissions::VIEW_ANY_MESSAGE)) {
          return AccessResult::allowed()->cachePerPermissions();
        }
        if ($account->hasPermission(Permissions::VIEW_OWN_MESSAGE)) {
          // Cast both sides: entity keys come back from storage as
          // strings (the MySQL driver stringifies fetches), so a strict
          // comparison without the cast denies every owner.
          $owner_id = (int) $session->getOwnerId();
          $account_id = (int) $account->id();
          $is_owner = $owner_id === $account_id;
          return AccessResult::allowedIf($is_owner)
            ->cachePerPermissions()
            ->cachePerUser()
            ->addCacheableDependency($session);
        }
        return AccessResult::forbidden()->cachePerPermissions();

      case 'delete':
        // Only admins can delete messages directly.
        return AccessResult::forbidden()->cachePerPermissions();

      default:
        return AccessResult::neutral();
    }
  }

  /**
   * {@inheritdoc}
   */
  protected function checkCreateAccess(AccountInterface $account, array $context, mixed $entity_bundle = NULL): AccessResultInterface {
    if ($account->hasPermission(FlowDropPermissions::ADMINISTER_FLOWDROP)) {
      return AccessResult::allowed()->cachePerPermissions();
    }

    if ($account->hasPermission(Permissions::ADMINISTER)) {
      return AccessResult::allowed()->cachePerPermissions();
    }

    if ($account->hasPermission(Permissions::EXECUTE_SESSION_WORKFLOW)) {
      return AccessResult::allowed()->cachePerPermissions();
    }

    return AccessResult::forbidden()->cachePerPermissions();
  }

}
