<?php

namespace Digtective\Controllers;

use Digtective\Base\Route;
use Digtective\Connectors\DigtectiveCoreConnector;
use Digtective\Repository\TokenRepository;
use Digtective\Repository\TokenRepositoryInterface;
use WP_REST_Request;

class ConnectionController{
    private const CONNECTION_ROUTE = "connection";
    private const GET_TOKEN_ROUTE = "get-token";
    private TokenRepositoryInterface $tokenRepository;
    private DigtectiveCoreConnector  $coreConnector;

    public function __construct(){
        $this->tokenRepository = new TokenRepository();

        if($this->tokenRepository->tableExists()){
            $token = $this->tokenRepository->getToken();
        }else {
            $token = "";
        }

        $this->coreConnector = new DigtectiveCoreConnector($token);
    }

    public function connect(WP_REST_Request $request){
        $token = $request["token"];

        $validationResponse = $this->coreConnector->validateToken($token);

        if(!$validationResponse->data){
            return [
                "status" =>
                    [
                        "code"    => 200,
                        "message" => "SUCCESS",
                        "error"   => "",
                    ],
                "data"   => false,
            ];
        }

        if($this->tokenRepository->hasToken()){
            $this->tokenRepository->update($token);

            return [
                "status" =>
                    [
                        "code"    => 200,
                        "message" => "SUCCESS",
                        "error"   => "",
                    ],
                "data"   => true,
            ];
        }

        return [
            "status" =>
                [
                    "code"    => 200,
                    "message" => "SUCCESS",
                    "error"   => "",
                ],
            "data"  => $this->tokenRepository->create($token),
        ];
    }

    public function getToken(){
        return $this->tokenRepository->getToken();
    }

    function adminOnly(){
        return current_user_can('manage_options');
    }

    public function register(){
        add_action("rest_api_init", function(){
            register_rest_route(
                Route::BASE_PATH, self::CONNECTION_ROUTE, [
                    "methods"  => "POST",
                    "callback" => [$this, "connect"],
                    "args"     => [
                        "token" => [
                            "required" => true,
                        ],
                    ],
                ]
            );
        });

        add_action("rest_api_init", function(){
            register_rest_route(
                Route::BASE_PATH, self::GET_TOKEN_ROUTE, [
                    "methods"             => "GET",
                    "callback"            => [$this, "getToken"],
                    "permission_callback" => [$this, "adminOnly"],
                ]
            );
        });
    }
}
