<?php

namespace ModernFields\FieldGroups\Services;

use ModernFields\FieldGroups\Entities\Field;

/**
 * Meta Service
 * 
 * Provides methods to get the sanitize callback and schema for a field.
 * 
 * @since 1.0.0
 */
class MetaService
{
  /**
   * Constructor
   * 
   * @since 1.0.0
   * @param Field $field The field entity.
   */
  public function __construct(
    protected Field $field
  ) {}

  /**
   * Get the appropriate sanitize callback based on field type
   *
   * @since 1.0.0
   * @return callable The sanitize callback
   */
  public function getSanitizeCallback(): callable
  {
    $mf_meta = $this->field->getAttribute('mfMeta') ?? [];

    # Use block-declared sanitize callback if available
    $callback = $mf_meta['sanitizeCallback'] ?? match ($this->field->getType()) {
      'number'  => 'sanitize_text_field',
      'boolean' => 'rest_sanitize_boolean',
      'array'   => 'rest_sanitize_array',
      'object'  => 'rest_sanitize_object',
      default   => 'sanitize_text_field',
    };

    return apply_filters('modern-fields/meta/sanitize_callback', $callback, $this->field);
  }

  /**
   * Get the schema for a field with a complex type (object, array).
   * 
   * For object types, returns the properties map.
   * For array types, returns the items definition.
   * 
   * @since 1.0.0
   * @return array The schema for the field.
   */
  public function getSchema(): array
  {
    $mf_meta = $this->field->getAttribute('mfMeta') ?? [];
    $schema = $mf_meta['schema'] ?? [];

    return apply_filters('modern-fields/meta/schema', $schema, $this->field);
  }
}
