<?php

declare(strict_types=1);

namespace Drupal\ffmpeg_media\Trait;

use Drupal\Core\Session\AccountInterface;
use Drupal\ffmpeg_media\Enum\ConversionStatus;
use Drupal\ffmpeg_media\ValueObject\ProgressData;

/**
 * Provides error message redaction for non-admin users.
 *
 * Classes using this trait must provide a current user account via the
 * abstract getErrorRedactionAccount() method.
 */
trait ErrorRedactionTrait {

  /**
   * Safe error message returned to non-admin users.
   */
  private const string SAFE_ERROR_MESSAGE = 'Conversion failed. Check logs for details.';

  /**
   * Returns the account to check permissions against.
   */
  abstract protected function getErrorRedactionAccount(): ?AccountInterface;

  /**
   * Returns TRUE when sensitive error details should be redacted.
   */
  protected function shouldRedactError(ProgressData $progress, mixed $error): bool {
    if ($progress->status !== ConversionStatus::Failed) {
      return FALSE;
    }

    if (!is_string($error) || $error === '') {
      return FALSE;
    }

    return !$this->getErrorRedactionAccount()?->hasPermission('administer ffmpeg media');
  }

  /**
   * Redacts an error string if the current user lacks admin permission.
   */
  protected function redactErrorString(?string $error): ?string {
    if ($error === NULL || $error === '') {
      return $error;
    }

    $account = $this->getErrorRedactionAccount();
    if ($account?->hasPermission('administer ffmpeg media')) {
      return $error;
    }

    return self::SAFE_ERROR_MESSAGE;
  }

}
