<?php

namespace Drupal\eb\Plugin\EbValidator;

use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\eb\Attribute\EbValidator;
use Drupal\eb\PluginBase\ValidatorBase;
use Drupal\eb\Result\ValidationResult;

/**
 * Validates that required fields are present.
 */
#[EbValidator(
  id: 'required_fields',
  label: new TranslatableMarkup('Required Fields Validator'),
  description: new TranslatableMarkup('Validates that all required operation fields are present'),
)]
class RequiredFieldsValidator extends ValidatorBase {

  /**
   * Required fields map per operation type.
   *
   * @var array<string, array<string>>
   */
  protected const REQUIRED_FIELDS_MAP = [
    'create_field' => ['field_name', 'field_type', 'entity_type', 'bundle', 'label'],
    'update_field' => ['field_name', 'entity_type', 'bundle'],
    'delete_field' => ['field_name', 'entity_type', 'bundle'],
    'create_bundle' => ['entity_type', 'bundle_id', 'label'],
    'update_bundle' => ['entity_type', 'bundle_id'],
    'delete_bundle' => ['entity_type', 'bundle_id'],
    'create_field_group' => ['entity_type', 'bundle', 'group_name', 'label'],
    'create_menu' => ['menu_id', 'label'],
    'configure_form_mode' => ['entity_type', 'bundle', 'field_name'],
    'configure_view_mode' => ['entity_type', 'bundle', 'field_name'],
  ];

  /**
   * {@inheritdoc}
   */
  public function validate(array $data): ValidationResult {
    $result = new ValidationResult();

    // Determine operation type from data (check both keys for consistency).
    $operationType = $this->getOperationType($data);

    if (!$operationType || !isset(self::REQUIRED_FIELDS_MAP[$operationType])) {
      // Cannot determine required fields, skip validation.
      return $result;
    }

    $requiredFields = self::REQUIRED_FIELDS_MAP[$operationType];
    $missingFields = [];

    foreach ($requiredFields as $field) {
      if (!isset($data[$field]) || $data[$field] === '') {
        $missingFields[] = $field;
      }
    }

    if (!empty($missingFields)) {
      $result->addError(
        $this->t('Missing required fields: @fields', [
          '@fields' => implode(', ', $missingFields),
        ]),
        '',
        'required_fields_missing'
      );
    }

    return $result;
  }

}
