<?php

declare(strict_types=1);

/**
 * Prominent Words REST API Controller (Task 8).
 *
 * Read-only endpoints:
 *
 *   GET  /prorank-seo/v1/prominent-words/{post_id}        — fetch stored payload
 *   POST /prorank-seo/v1/prominent-words/index/{post_id}  — index one post
 *   POST /prorank-seo/v1/prominent-words/bulk-index       — capped batch index
 *
 * @package ProRank\SEO\Core\RestApi
 * @since   1.3.1
 */

namespace ProRank\SEO\Core\RestApi;

use ProRank\SEO\Core\Content\ProminentWordsAnalyzer;
use WP_REST_Request;
use WP_REST_Server;
use WP_Error;

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


class ProminentWordsController extends BaseController {

    public function __construct() {
        $this->rest_base = 'prominent-words';
    }

    public function register_routes(): void {
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/(?P<post_id>\d+)',
            [
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => [ $this, 'get_one' ],
                'permission_callback' => [ $this, 'check_can_read_post' ],
                'args'                => [
                    'post_id' => [
                        'type'     => 'integer',
                        'required' => true,
                        'minimum'  => 1,
                    ],
                ],
            ]
        );

        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/index/(?P<post_id>\d+)',
            [
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => [ $this, 'index_one' ],
                'permission_callback' => [ $this, 'check_can_edit_post' ],
                'args'                => [
                    'post_id' => [
                        'type'     => 'integer',
                        'required' => true,
                        'minimum'  => 1,
                    ],
                    'force'   => [
                        'type'    => 'boolean',
                        'default' => false,
                    ],
                ],
            ]
        );

        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/bulk-index',
            [
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => [ $this, 'bulk_index' ],
                'permission_callback' => [ $this, 'check_permission_edit_posts' ],
                'args'                => [
                    'limit'  => [
                        'type'    => 'integer',
                        'default' => ProminentWordsAnalyzer::BULK_CAP,
                        'minimum' => 1,
                        'maximum' => ProminentWordsAnalyzer::BULK_CAP,
                    ],
                    'offset' => [
                        'type'    => 'integer',
                        'default' => 0,
                        'minimum' => 0,
                    ],
                ],
            ]
        );
    }

    public function get_one( WP_REST_Request $request ) {
        return $this->try_callback( function () use ( $request ) {
            $post_id = (int) $request->get_param( 'post_id' );
            $payload = ProminentWordsAnalyzer::get_post_index( $post_id );
            return $this->get_success_response( $payload );
        } );
    }

    public function index_one( WP_REST_Request $request ) {
        return $this->try_callback( function () use ( $request ) {
            $post_id = (int) $request->get_param( 'post_id' );
            $force   = (bool) $request->get_param( 'force' );
            $result  = ProminentWordsAnalyzer::index_post( $post_id, $force );
            return $this->get_success_response( $result );
        } );
    }

    public function bulk_index( WP_REST_Request $request ) {
        return $this->try_callback( function () use ( $request ) {
            $limit  = (int) $request->get_param( 'limit' );
            $offset = (int) $request->get_param( 'offset' );
            $summary = ProminentWordsAnalyzer::bulk_index( $limit, $offset );
            return $this->get_success_response( $summary );
        } );
    }

    /**
     * Per-post read permission: any user who can read the post.
     */
    public function check_can_read_post( WP_REST_Request $request ) {
        $post_id = (int) $request->get_param( 'post_id' );
        if ( $post_id <= 0 ) {
            return $this->get_error_response( __( 'Invalid post id.', 'prorank-seo' ), 400, 'invalid_post' );
        }
        if ( ! function_exists( 'current_user_can' ) || ! current_user_can( 'read_post', $post_id ) ) {
            return new WP_Error(
                'rest_forbidden',
                __( 'You do not have permission to read this post.', 'prorank-seo' ),
                [ 'status' => 403 ]
            );
        }
        return true;
    }

    /**
     * Per-post write permission for single-post indexing.
     */
    public function check_can_edit_post( WP_REST_Request $request ) {
        $post_id = (int) $request->get_param( 'post_id' );
        if ( $post_id <= 0 ) {
            return $this->get_error_response( __( 'Invalid post id.', 'prorank-seo' ), 400, 'invalid_post' );
        }
        if ( ! function_exists( 'current_user_can' ) || ! current_user_can( 'edit_post', $post_id ) ) {
            return new WP_Error(
                'rest_forbidden',
                __( 'You do not have permission to edit this post.', 'prorank-seo' ),
                [ 'status' => 403 ]
            );
        }
        return true;
    }
}
