<?php
/**
 * Comments REST Controller — Admin-only CRUD for comments & discussions.
 *
 * Routes:
 *   GET    /titancart/v1/admin/comments           List (filterable by object_type, status, rating, search)
 *   POST   /titancart/v1/admin/comments           Create
 *   GET    /titancart/v1/admin/comments/{id}      Single
 *   PUT    /titancart/v1/admin/comments/{id}      Update
 *   DELETE /titancart/v1/admin/comments/{id}      Delete
 *   PUT    /titancart/v1/admin/comments/{id}/status  Approve/reject
 *   GET    /titancart/v1/admin/comments/stats      Stats by type + status
 *
 * @package TitanCart\REST\Comments
 */

namespace TitanCart\REST\Comments;

use TitanCart\Modules\Comments\CommentsManager;
use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;

defined( 'ABSPATH' ) || exit;

class CommentsController {

    private string $ns = 'titancart/v1';
    private CommentsManager $mgr;

    public function __construct() {
        $this->mgr = new CommentsManager();
    }

    public function register_routes(): void {

        register_rest_route( $this->ns, '/admin/comments', [
            [
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => [ $this, 'list_comments' ],
                'permission_callback' => [ $this, 'admin_check' ],
                'args'                => [
                    'object_type' => [ 'type' => 'string' ],
                    'status'      => [ 'type' => 'string' ],
                    'rating'      => [ 'type' => 'integer' ],
                    'search'      => [ 'type' => 'string' ],
                    'page'        => [ 'type' => 'integer', 'default' => 1 ],
                    'per_page'    => [ 'type' => 'integer', 'default' => 20 ],
                ],
            ],
            [
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => [ $this, 'create_comment' ],
                'permission_callback' => [ $this, 'admin_check' ],
            ],
        ] );

        register_rest_route( $this->ns, '/admin/comments/stats', [
            [
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => [ $this, 'get_stats' ],
                'permission_callback' => [ $this, 'admin_check' ],
            ],
        ] );

        register_rest_route( $this->ns, '/admin/comments/(?P<id>\d+)', [
            [
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => [ $this, 'get_comment' ],
                'permission_callback' => [ $this, 'admin_check' ],
            ],
            [
                'methods'             => WP_REST_Server::EDITABLE,
                'callback'            => [ $this, 'update_comment' ],
                'permission_callback' => [ $this, 'admin_check' ],
            ],
            [
                'methods'             => WP_REST_Server::DELETABLE,
                'callback'            => [ $this, 'delete_comment' ],
                'permission_callback' => [ $this, 'admin_check' ],
            ],
        ] );

        register_rest_route( $this->ns, '/admin/comments/(?P<id>\d+)/status', [
            [
                'methods'             => WP_REST_Server::EDITABLE,
                'callback'            => [ $this, 'set_status' ],
                'permission_callback' => [ $this, 'admin_check' ],
            ],
        ] );
    }

    // ── Handlers ─────────────────────────────────────────────────────────────

    public function list_comments( WP_REST_Request $request ): WP_REST_Response {
        return new WP_REST_Response( $this->mgr->get_list( $request->get_params() ) );
    }

    public function get_comment( WP_REST_Request $request ): WP_REST_Response|WP_Error {
        $row = $this->mgr->get( (int) $request['id'] );
        return $row ? new WP_REST_Response( $row ) : new WP_Error( 'not_found', 'Comment not found.', [ 'status' => 404 ] );
    }

    public function create_comment( WP_REST_Request $request ): WP_REST_Response {
        $result = $this->mgr->create( $request->get_json_params() ?: [] ); // KI-85 — typed `array $data` ⇒ TypeError on a non-JSON body
        return new WP_REST_Response( $result, $result['success'] ? 201 : 422 );
    }

    public function update_comment( WP_REST_Request $request ): WP_REST_Response {
        $result = $this->mgr->update( (int) $request['id'], $request->get_json_params() ?: [] ); // KI-85
        return new WP_REST_Response( $result );
    }

    public function delete_comment( WP_REST_Request $request ): WP_REST_Response {
        return new WP_REST_Response( $this->mgr->delete( (int) $request['id'] ) );
    }

    public function set_status( WP_REST_Request $request ): WP_REST_Response {
        $body   = $request->get_json_params();
        $status = $body['status'] ?? '';
        if ( ! in_array( $status, [ 'pending', 'approved', 'rejected' ], true ) ) {
            return new WP_REST_Response( [ 'success' => false, 'message' => 'Invalid status.' ], 422 );
        }
        return new WP_REST_Response( $this->mgr->set_status( (int) $request['id'], $status ) );
    }

    public function get_stats( WP_REST_Request $request ): WP_REST_Response {
        return new WP_REST_Response( $this->mgr->stats() );
    }

    public function admin_check(): bool {
        return current_user_can( 'manage_options' );
    }
}
