<?php

namespace WordpressModelsTests;

use PHPUnit\Framework\TestCase;
use WordpressModels\Rest\AbstractRestApi;
use WordpressModels\Rest\Attribute\RestRoute;

class RestApiControllerTest extends TestCase
{

    private AbstractRestApi $api;

    protected function setUp(): void
    {
        $this->api = new class extends AbstractRestApi {

            public function __construct()
            {
                parent::__construct('testNs');
            }

            public function getRouteDefinitions(): array
            {
                return $this->routeDefinitions;
            }

            #[RestRoute(
                'testRoute',
                ['GET'],
                '__return_true',
                [
                    'testParam' => [
                        'type' => 'string',
                        'required' => true
                    ]
                ]
            )]
            public function testRoute(\WP_REST_Request $request) {
                return ['result' => $request->get_param('testParam')];
            }

        };
    }

    public function testRouteIsRegistered()
    {
        do_action('rest_api_init');

        $def = current($this->api->getRouteDefinitions());


        self::assertEquals('testRoute', $def['route']);
        self::assertEquals([$this->api, 'testRoute'], $def['args']['callback']);
    }

    public function testRouteRejectedInvalidParams()
    {
        do_action('rest_api_init');

        $response = rest_get_server()->dispatch(new \WP_REST_Request('GET', '/testNs/testRoute', []));

        self::assertEquals('rest_missing_callback_param', $response->data['code']);
        self::assertEquals('testParam', current($response->data['data']['params']));
    }

    public function testRouteReturnsInputParam()
    {
        do_action('rest_api_init');

        $request = new \WP_REST_Request('GET', '/testNs/testRoute');
        $value = 'TestValue';
        $request->set_param('testParam', $value);
        $response = rest_get_server()->dispatch($request);

        self::assertEquals($value, $response->data['result']);
    }

}