<?php

namespace OtomaticAi\Utils;

use OtomaticAi\Vendors\Illuminate\Support\Str;
use WP_REST_Request;

abstract class Route
{
    static public function ajax($key, $class, $func = "__invoke")
    {
        add_action("wp_ajax_otomatic_ai_" . $key, function () use ($class, $func) {
            call_user_func([new $class, $func]);
        });
    }

    static public function rest($method, $endpoint, $class, $func = "__invoke")
    {
        add_action('rest_api_init', function () use ($method, $endpoint, $class, $func) {
            register_rest_route('otomatic-ai/v1', '/' . Str::of($endpoint)->ltrim('/'), [
                'methods' => $method,
                'callback' => function (WP_REST_Request $request) use ($class, $func) {
                    return call_user_func([new $class($request), $func], $request);
                },
                'permission_callback' => function (WP_REST_Request $request) {
                    return Auth::authorizeRestApi($request);
                },
            ]);
        });
    }
}
