<?php
declare(strict_types=1);

namespace AuxCF\Entities\Settings\Traits;

/**
 * Provides utility methods for working with settings based on Enum-like classes.
 * This trait offers functionalities to retrieve enum options, construct formatted
 * option lists, and safely handle enum lookup by name.
 *
 * @since 1.0.0
 */
trait SettingEnumTraits
{
  /**
   * Get a list of all enum options values
   * @since 1.0.0
   */
  public static function getOptions(): array
  {
    $options = array_column(self::cases(), 'value');

    return $options;
  }

  /**
   * Get a comma-separated list of all enum options values
   * @since 1.0.0
   */
  public static function getOptionsList(): string
  {
    return "'" . join("', '", self::getOptions()) . "'";
  }

  /**
   * Get a human-readable list of all enum options values
   * @since 1.0.0
   */
  public static function getVerboseOptionsList(): string
  {
    $optionsList = [];

    $options = self::getOptions();
    $optionsCount = count($options);

    foreach ($options as $optionIndex => $option) {
      $or = $optionIndex === $optionsCount - 1 && $optionsCount > 1 ? "or " : "";
      $optionsList[] = $or . "'{$option}'";
    }

    return join(", ", $optionsList);
  }

  /**
   * Attempt to match an enum value to a string value
   * @since 1.0.0
   */
  public static function tryFromName(string|int $name): self|null
  {
    $enum = null;

    try {
      $enum = self::from($name);
    } catch ( \ValueError $e) {
      $options = self::getVerboseOptionsList();
      $field = self::SETTING_LABEL;

      print("'{$name}' is not a valid {$field} value. Try {$options}.");
    }

    return $enum;
  }
}
