<?php

namespace ModernFields\Sync\Hooks;

use ModernFields\Sync\Services\JsonSyncService;
use ModernFields\WordPress\Interfaces\Hooks;
use ModernFields\WordPress\Traits\ChecksPermissions;

use WP_Post;
use WP_REST_Request;
use WP_REST_Response;

defined('ABSPATH') || exit;

/**
 * Writes field group JSON files on save and exposes REST endpoints for sync.
 *
 * @since 0.8
 */
class AdminSyncGroups implements Hooks
{
  use ChecksPermissions;

  public function __construct(
    protected JsonSyncService $jsonSyncService,
  ) {}

  /**
   * @since 0.8
   */
  public function registerHooks(): void
  {
    # Priority 20 — runs after FieldIndexer (10) so the group is fully indexed
    add_action('save_post', [$this, 'onSavePost'], 20, 2);
    add_action('rest_api_init', [$this, 'registerRestEndpoints']);
  }

  /**
   * @since 0.8
   */
  public function onSavePost(int $post_id, WP_Post $post): void
  {
    if ($post->post_type !== MODERN_FIELDS_CPT_SLUG) {
      return;
    }

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

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

    if ($post->post_status === 'trash') {
      $this->jsonSyncService->deleteGroupJson($post_id);
      return;
    }

    $this->jsonSyncService->writeGroupJson($post_id);
  }

  /**
   * @since 0.8
   */
  public function registerRestEndpoints(): void
  {
    register_rest_route(MODERN_FIELDS_REST_NAMESPACE, '/sync/status', [
      'methods'             => 'GET',
      'callback'            => [$this, 'handleGetStatus'],
      'permission_callback' => [$this, 'checkPermissions'],
    ]);

    register_rest_route(MODERN_FIELDS_REST_NAMESPACE, '/sync', [
      'methods'             => 'POST',
      'callback'            => [$this, 'handleSync'],
      'permission_callback' => [$this, 'checkPermissions'],
      'args'                => [
        'uuid' => [
          'type'              => 'string',
          'required'          => true,
          'sanitize_callback' => 'sanitize_text_field',
        ],
      ],
    ]);
  }

  /**
   * @since 0.8
   */
  public function handleGetStatus(WP_REST_Request $request): WP_REST_Response
  {
    return rest_ensure_response($this->jsonSyncService->getAllSyncStatuses());
  }

  /**
   * @since 0.8
   */
  public function handleSync(WP_REST_Request $request): WP_REST_Response
  {
    $uuid   = $request->get_param('uuid');
    $report = $this->jsonSyncService->importFromJson($uuid);

    if (isset($report['error'])) {
      return new WP_REST_Response(['message' => $report['error']], 400);
    }

    return rest_ensure_response($report);
  }


}
