<?php

declare(strict_types=1);

namespace PrettyLinks\Pro\Rest;

use PrettyLinks\Pro\Options\Store as ProOptionsStore;
use PrettyLinks\Pro\Redirect\MuPluginInstaller;
use PrettyLinks\Pro\Tools\DuplicateKeywords;
use PrettyLinks\Rest\Controllers\BaseController;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

/**
 * Pro-only Tools page endpoints. Lite owns `/tools/export` and
 * `/tools/import`; Pro owns the MU-dispatch toggle and the keyword
 * de-duplication scanner.
 */
class ToolsController extends BaseController
{
    /**
     * Register the Pro Tools REST routes.
     *
     * @return void
     */
    public function register(): void
    {
        register_rest_route($this->namespace(), '/tools/duplicate-keywords', [
            [
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => [$this, 'scanDuplicateKeywords'],
                'permission_callback' => $this->permission(),
            ],
        ]);

        register_rest_route($this->namespace(), '/tools/duplicate-keywords/resolve', [
            [
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => [$this, 'resolveDuplicateKeyword'],
                'permission_callback' => $this->permission(),
                'args'                => [
                    'keep_keyword_id' => [
                        'type'     => 'integer',
                        'required' => true,
                    ],
                ],
            ],
        ]);

        register_rest_route($this->namespace(), '/tools/mu-dispatch', [
            [
                'methods'             => WP_REST_Server::EDITABLE,
                'callback'            => [$this, 'muDispatch'],
                'permission_callback' => $this->permission(),
            ],
        ]);
    }

    /**
     * Toggle the MU-plugin redirect dispatcher on or off.
     *
     * @param WP_REST_Request $request Incoming REST request.
     *
     * @return WP_REST_Response
     */
    public function muDispatch(WP_REST_Request $request): WP_REST_Response
    {
        $enable    = (bool) ($request->get_json_params()['enable'] ?? false);
        $installer = $this->container->get(MuPluginInstaller::class);
        $ok        = $enable ? $installer->install() : $installer->uninstall();
        $this->container->get(ProOptionsStore::class)->set('mu_dispatch', $enable && $ok);
        return new WP_REST_Response([
            'enabled' => $enable && $ok,
            'ok'      => $ok,
        ]);
    }

    /**
     * Scan for duplicate-keyword groups.
     *
     * @return WP_REST_Response
     */
    public function scanDuplicateKeywords(): WP_REST_Response
    {
        return new WP_REST_Response([
            'groups' => $this->service()->findGroups(),
        ]);
    }

    /**
     * Resolve a duplicate-keyword group by keeping one keyword.
     *
     * @param WP_REST_Request $request Incoming REST request.
     *
     * @return WP_REST_Response
     */
    public function resolveDuplicateKeyword(WP_REST_Request $request): WP_REST_Response
    {
        $keepId = (int) $request->get_param('keep_keyword_id');
        if ($keepId <= 0) {
            return new WP_REST_Response(['error' => 'invalid_params'], 422);
        }
        $result = $this->service()->resolve($keepId);
        if ($result['kept'] === 0) {
            return new WP_REST_Response(['error' => 'keep_not_found'], 404);
        }
        return new WP_REST_Response($result);
    }

    /**
     * Resolve the duplicate-keywords service from the container.
     *
     * @return DuplicateKeywords
     */
    private function service(): DuplicateKeywords
    {
        return $this->container->get(DuplicateKeywords::class);
    }
}
