<?php

declare(strict_types=1);

namespace Drupal\api_monitor_client\Entity;

use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityPublishedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\StringTranslation\TranslatableMarkup;

/**
 * Defines the Api Monitor Manual entity.
 *
 * @ContentEntityType(
 *   id = "api_monitor_manual",
 *   label = @Translation("API Monitor Manual Endpoint"),
 *   label_collection = @Translation("Manual Endpoints"),
 *   label_singular = @Translation("manual endpoint"),
 *   label_plural = @Translation("manual endpoints"),
 *   label_count = @PluralTranslation(
 *     singular = "@count manual endpoint",
 *     plural = "@count manual endpoints",
 *   ),
 *   handlers = {
 *     "list_builder" = "Drupal\api_monitor_client\ApiMonitorManualListBuilder",
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "views_data" = "Drupal\views\EntityViewsData",
 *     "form" = {
 *       "add" = "Drupal\api_monitor_client\Form\ApiMonitorManualForm",
 *       "edit" = "Drupal\api_monitor_client\Form\ApiMonitorManualForm",
 *       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
 *     },
 *     "route_provider" = {
 *       "html" = "Drupal\Core\Entity\Routing\AdminHtmlRouteProvider",
 *     },
 *   },
 *   base_table = "api_monitor_manual",
 *   data_table = "api_monitor_manual_field_data",
 *   translatable = FALSE,
 *   admin_permission = "administer api_monitor_manual",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "title",
 *     "uuid" = "uuid",
 *     "published" = "status",
 *   },
 *   links = {
 *     "canonical" = "/admin/config/development/api-monitoring/manual/{api_monitor_manual}",
 *     "add-form" = "/admin/config/development/api-monitoring/manual/add",
 *     "edit-form" = "/admin/config/development/api-monitoring/manual/{api_monitor_manual}/edit",
 *     "delete-form" = "/admin/config/development/api-monitoring/manual/{api_monitor_manual}/delete",
 *     "collection" = "/admin/config/development/api-monitoring/manual",
 *   },
 *   field_ui_base_route = "entity.api_monitor_manual.collection",
 * )
 */
class ApiMonitorManual extends ContentEntityBase implements ApiMonitorManualInterface {
  use EntityPublishedTrait;

  /**
   * {@inheritdoc}
   */
  public function getApiId(): string {
    return $this->get('api_id')->value ?? '';
  }

  /**
   * {@inheritdoc}
   */
  public function getProvider(): ?ApiMonitorProviderInterface {
    $provider_id = $this->get('provider')->target_id;
    if (!$provider_id) {
      return NULL;
    }
    return $this->entityTypeManager()
      ->getStorage('api_monitor_provider')
      ->load($provider_id);
  }

  /**
   * {@inheritdoc}
   */
  public function getEndpointPath(): string {
    return $this->get('endpoint_path')->value ?? '';
  }

  /**
   * {@inheritdoc}
   */
  public function getMethod(): string {
    return $this->get('method')->value ?? 'GET';
  }

  /**
   * {@inheritdoc}
   */
  public function getHeaders(): array {
    $headers = $this->get('headers')->value;
    return $headers ? json_decode($headers, TRUE) : [];
  }

  /**
   * {@inheritdoc}
   */
  public function getBody(): ?string {
    return $this->get('body')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function getAuthType(): string {
    return $this->get('auth_type')->value ?? 'inherit';
  }

  /**
   * {@inheritdoc}
   */
  public function getAuthCredentials(): ?string {
    return $this->get('auth_credentials')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function getAuthHeaderName(): ?string {
    return $this->get('auth_header_name')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function getProbePlugin(): ?string {
    return $this->get('probe_plugin')->value;
  }

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type): array {
    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['title'] = BaseFieldDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Title'))
      ->setRequired(TRUE)
      ->setSetting('max_length', 255)
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -5,
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['api_id'] = BaseFieldDefinition::create('string')
      ->setLabel(new TranslatableMarkup('API ID'))
      ->setDescription(new TranslatableMarkup('Unique machine name for this endpoint (e.g., custom_users_get).'))
      ->setRequired(TRUE)
      ->setSetting('max_length', 128)
      ->addConstraint('UniqueField')
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -4,
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['provider'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(new TranslatableMarkup('Provider'))
      ->setDescription(new TranslatableMarkup('The API provider this endpoint belongs to.'))
      ->setSetting('target_type', 'api_monitor_provider')
      ->setRequired(TRUE)
      ->setDisplayOptions('form', [
        'type' => 'entity_reference_autocomplete',
        'weight' => -3,
        'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => 60,
          'placeholder' => '',
        ],
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['endpoint_path'] = BaseFieldDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Endpoint Path'))
      ->setDescription(new TranslatableMarkup('The API path (e.g., /api/v1/users). Can be relative to provider URL or absolute.'))
      ->setRequired(TRUE)
      ->setSetting('max_length', 512)
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -2,
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['method'] = BaseFieldDefinition::create('list_string')
      ->setLabel(new TranslatableMarkup('HTTP Method'))
      ->setRequired(TRUE)
      ->setSetting('allowed_values', [
        'GET' => 'GET',
        'POST' => 'POST',
        'PUT' => 'PUT',
        'PATCH' => 'PATCH',
        'DELETE' => 'DELETE',
      ])
      ->setDefaultValue('GET')
      ->setDisplayOptions('form', [
        'type' => 'options_select',
        'weight' => -1,
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['headers'] = BaseFieldDefinition::create('string_long')
      ->setLabel(new TranslatableMarkup('Custom Headers'))
      ->setDescription(new TranslatableMarkup('JSON object of custom headers. Leave empty to use provider defaults.'))
      ->setSetting('rows', 3)
      ->setDisplayOptions('form', [
        'type' => 'string_textarea',
        'weight' => 0,
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['body'] = BaseFieldDefinition::create('string_long')
      ->setLabel(new TranslatableMarkup('Request Body'))
      ->setDescription(new TranslatableMarkup('Request body for POST/PUT/PATCH requests.'))
      ->setSetting('rows', 5)
      ->setDisplayOptions('form', [
        'type' => 'string_textarea',
        'weight' => 1,
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['auth_type'] = BaseFieldDefinition::create('list_string')
      ->setLabel(new TranslatableMarkup('Authentication Type'))
      ->setDescription(new TranslatableMarkup('Override the provider authentication settings.'))
      ->setRequired(TRUE)
      ->setSetting('allowed_values', [
        'inherit' => new TranslatableMarkup('Inherit from Provider'),
        'oauth2' => new TranslatableMarkup('OAuth2 (use provider credentials)'),
        'api_key' => new TranslatableMarkup('API Key'),
        'bearer' => new TranslatableMarkup('Bearer Token'),
        'none' => new TranslatableMarkup('No Authentication'),
      ])
      ->setDefaultValue('inherit')
      ->setDisplayOptions('form', [
        'type' => 'options_select',
        'weight' => 2,
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['auth_credentials'] = BaseFieldDefinition::create('string_long')
      ->setLabel(new TranslatableMarkup('Auth Credentials'))
      ->setDescription(new TranslatableMarkup('API Key or Bearer Token. Use key module reference or direct value.'))
      ->setSetting('rows', 2)
      ->setDisplayOptions('form', [
        'type' => 'string_textarea',
        'weight' => 3,
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['auth_header_name'] = BaseFieldDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Auth Header Name'))
      ->setDescription(new TranslatableMarkup('Custom header name for API Key (e.g., X-API-Key, X-Custom-Auth). Required when using API Key authentication.'))
      ->setSetting('max_length', 128)
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => 3,
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['probe_plugin'] = BaseFieldDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Probe Plugin'))
      ->setDescription(new TranslatableMarkup('Optional probe plugin for validation logic.'))
      ->setSetting('max_length', 128)
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => 4,
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['status'] = BaseFieldDefinition::create('boolean')
      ->setLabel(new TranslatableMarkup('Published'))
      ->setDefaultValue(TRUE)
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'weight' => 10,
      ])
      ->setDisplayConfigurable('form', TRUE);

    return $fields;
  }

}
