<?php

declare(strict_types=1);


namespace ProRank\SEO\Core\RestApi;

use WP_REST_Controller;
use WP_REST_Server;
use WP_REST_Response;
use WP_Error;
use ProRank\SEO\Services\Cdn\CdnManager;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}




class CdnController extends WP_REST_Controller {
    protected $namespace = 'prorank-seo/v1';
    protected $rest_base = 'cdn';

    public function register_routes() {
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/test',
            [
                [
                    'methods'             => WP_REST_Server::READABLE,
                    'callback'            => [ $this, 'test_connection' ],
                    'permission_callback' => [ $this, 'permissions_check' ],
                ],
                [
                    'methods'             => WP_REST_Server::CREATABLE,
                    'callback'            => [ $this, 'test_connection' ],
                    'permission_callback' => [ $this, 'permissions_check' ],
                ],
            ]
        );

        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/purge',
            [
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => [ $this, 'purge' ],
                'permission_callback' => [ $this, 'permissions_check' ],
                'args'                => [
                    'urls' => [
                        'type' => 'array',
                        'required' => false,
                    ],
                ],
            ]
        );
    }

    public function permissions_check() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return new WP_Error( 'rest_forbidden', __( 'You do not have permission to manage CDN.', 'prorank-seo' ), [ 'status' => 403 ] );
        }
        return true;
    }

    public function test_connection( $request = null ) {
        $settings = [];
        if ( $request instanceof \WP_REST_Request ) {
            $candidate = $request->get_param( 'settings' );
            if ( is_array( $candidate ) ) {
                $settings = $candidate;
            }
        }

        $cdn = new CdnManager();
        $result = $cdn->test_connection( $settings );

        if ( is_wp_error( $result ) ) {
            return $result;
        }

        return new WP_REST_Response( [ 'success' => true, 'result' => $result ], 200 );
    }

    public function purge( $request ) {
        $cdn = new CdnManager();
        $urls = $request->get_param( 'urls' );

        if ( $urls && is_array( $urls ) ) {
            $result = $cdn->purge_urls( $urls );
        } else {
            $result = $cdn->purge_all();
        }

        if ( is_wp_error( $result ) ) {
            return $result;
        }

        return new WP_REST_Response( [ 'success' => true ], 200 );
    }
}
