<?php

namespace ModernFields\FieldGroups\Hooks;

use ModernFields\WordPress\Interfaces\Hooks;

use WP_Post;

defined('ABSPATH') || exit;

/**
 * Generates and persists a stable UUID for each field group, CPT definition,
 * taxonomy definition, and block definition so they can be matched across sites
 * during import.
 *
 * @since 0.7.2
 */
class UuidGenerator implements Hooks
{
  /**
   * @since 0.7.2
   */
  public function registerHooks(): void
  {
    add_action('save_post', [$this, 'ensureUuid'], 10, 2);
    add_action('init', [$this, 'registerMetaField']);
  }

  /**
   * Registers the mf_uuid meta field for all tracked post types.
   *
   * The UUID is an internal implementation detail used by the import/export
   * feature to match items across sites. It is not exposed via the REST API.
   *
   * @since 0.7.2
   */
  public function registerMetaField(): void
  {
    $args = [
      'type'         => 'string',
      'description'  => __('Stable UUID used to match items during import/export', 'modern-fields'),
      'single'       => true,
      'show_in_rest' => false,
      'default'      => '',
    ];

    register_post_meta(MODERN_FIELDS_CPT_SLUG, 'mf_uuid', $args);
    register_post_meta(MODERN_FIELDS_POST_TYPES_CPT_SLUG, 'mf_uuid', $args);
    register_post_meta(MODERN_FIELDS_TAXONOMIES_CPT_SLUG, 'mf_uuid', $args);
    register_post_meta(MODERN_FIELDS_BLOCKS_CPT_SLUG, 'mf_uuid', $args);
  }

  /**
   * Generates a UUID for newly saved posts that do not yet have one.
   *
   * Runs for mf_field_group, mf_post_type, mf_taxonomy and mf_block post types.
   * Skips autosaves and revisions.
   *
   * @since 0.7.2
   * @param int     $post_id The post ID being saved.
   * @param WP_Post $post    The post object being saved.
   */
  public function ensureUuid(int $post_id, WP_Post $post): void
  {
    $tracked_types = [
      MODERN_FIELDS_CPT_SLUG,
      MODERN_FIELDS_POST_TYPES_CPT_SLUG,
      MODERN_FIELDS_TAXONOMIES_CPT_SLUG,
      MODERN_FIELDS_BLOCKS_CPT_SLUG,
    ];

    if (!in_array($post->post_type, $tracked_types, true)) {
      return;
    }

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
      return;
    }

    if (wp_is_post_revision($post_id)) {
      return;
    }

    $existing = get_post_meta($post_id, 'mf_uuid', true);

    if (empty($existing)) {
      update_post_meta($post_id, 'mf_uuid', wp_generate_uuid4());
    }
  }
}
