<?php

namespace ModernFields\ImportExport\Hooks;

use ModernFields\ImportExport\Services\ExportService;
use ModernFields\ImportExport\Services\ImportService;
use ModernFields\WordPress\Interfaces\Hooks;
use ModernFields\WordPress\Traits\ChecksPermissions;

use WP_REST_Request;
use WP_REST_Response;

defined('ABSPATH') || exit;

/**
 * Registers the Import / Export admin page and REST endpoints.
 *
 * @since 0.8
 */
class AdminImportExport implements Hooks
{
  use ChecksPermissions;

  public function __construct(
    protected ExportService $exportService,
    protected ImportService $importService,
  ) {}

  /**
   * @since 0.8
   */
  public function registerHooks(): void
  {
    add_action('rest_api_init', [$this, 'registerRestEndpoints']);
  }

  /**
   * @since 0.8
   */
  public function registerRestEndpoints(): void
  {
    register_rest_route(MODERN_FIELDS_REST_NAMESPACE, '/export', [
      'methods'             => 'POST',
      'callback'            => [$this, 'handleExport'],
      'permission_callback' => [$this, 'checkPermissions'],
      'args'                => [
        'group_ids' => [
          'type'    => 'array',
          'default' => [],
          'items'   => ['type' => 'integer'],
        ],
        'post_type_ids' => [
          'type'    => 'array',
          'default' => [],
          'items'   => ['type' => 'integer'],
        ],
        'taxonomy_ids' => [
          'type'    => 'array',
          'default' => [],
          'items'   => ['type' => 'integer'],
        ],
        'block_ids' => [
          'type'    => 'array',
          'default' => [],
          'items'   => ['type' => 'integer'],
        ],
      ],
    ]);

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

  /**
   * @since 0.8
   */
  public function handleExport(WP_REST_Request $request): WP_REST_Response
  {
    $params = $request->get_json_params() ?? [];

    $group_ids     = array_map('absint', (array) ($params['group_ids'] ?? []));
    $post_type_ids = array_map('absint', (array) ($params['post_type_ids'] ?? []));
    $taxonomy_ids  = array_map('absint', (array) ($params['taxonomy_ids'] ?? []));
    $block_ids     = array_map('absint', (array) ($params['block_ids'] ?? []));

    $data = $this->exportService->export($group_ids, $post_type_ids, $taxonomy_ids, $block_ids);

    return rest_ensure_response($data);
  }

  /**
   * The request body must be the JSON export payload (optionally with an
   * extra force_uuids key listing UUIDs whose conflict should be ignored).
   *
   * @since 0.8
   */
  public function handleImport(WP_REST_Request $request): WP_REST_Response
  {
    $params = $request->get_json_params();

    if (empty($params) || !isset($params['mf_version'])) {
      return new WP_REST_Response(
        ['message' => __('Invalid import file.', 'modern-fields')],
        400
      );
    }

    $force_uuids = array_map('sanitize_text_field', (array) ($params['force_uuids'] ?? []));
    $report      = $this->importService->import($params, $force_uuids);

    return rest_ensure_response($report);
  }
}
