<?php

namespace ModernFields\Sync\Hooks;

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

use WP_REST_Request;
use WP_REST_Response;

defined('ABSPATH') || exit;

/**
 * Wires block definition JSON sync to WordPress hooks and REST API.
 *
 * Writes a JSON file to mf-json/ on every block definition save, and exposes
 * REST endpoints for reading sync status and triggering sync.
 *
 * @since 1.0.3
 */
class AdminSyncBlocks implements Hooks
{
  use ChecksPermissions;

  public function __construct(
    protected JsonSyncBlockService $syncService,
  ) {}

  public function registerHooks(): void
  {
    add_action('save_post', [$this, 'onSavePost'], 20, 2);
    add_action('rest_api_init', [$this, 'registerRestEndpoints']);
  }

  public function onSavePost(int $post_id, \WP_Post $post): void
  {
    if ($post->post_type !== MODERN_FIELDS_BLOCKS_CPT_SLUG) {
      return;
    }

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

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

    $this->syncService->writeDefinitionJson($post_id);
  }

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

    register_rest_route(MODERN_FIELDS_REST_NAMESPACE, '/sync/block', [
      'methods'             => 'POST',
      'callback'            => [$this, 'handleSync'],
      'permission_callback' => [$this, 'checkPermissions'],
    ]);
  }

  public function handleGetStatus(WP_REST_Request $request): WP_REST_Response
  {
    return rest_ensure_response($this->syncService->getAllSyncStatuses());
  }

  public function handleSync(WP_REST_Request $request): WP_REST_Response
  {
    $key    = sanitize_key($request->get_param('key') ?? '');
    $report = $this->syncService->importFromJson($key);

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

    return rest_ensure_response($report);
  }
}
