<?php
/**
 * REST API — Chief Insights (newsroom-os/v1).
 *
 * @package Newsroom_AI_Assistant
 */

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

add_action( 'rest_api_init', 'newsai_register_insights_rest_routes' );

if ( ! function_exists( 'newsai_register_insights_rest_routes' ) ) {
	function newsai_register_insights_rest_routes() {
		register_rest_route(
			'newsroom-os/v1',
			'/insights',
			[
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => 'newsai_rest_get_insights',
				'permission_callback' => 'newsai_rest_insights_can_view',
				'args'                => [
					'days' => [
						'type'              => 'integer',
						'default'           => 30,
						'sanitize_callback' => static function ( $v ) {
							return max( 7, min( 90, (int) $v ) );
						},
					],
				],
			]
		);
	}
}

if ( ! function_exists( 'newsai_rest_insights_can_view' ) ) {
	function newsai_rest_insights_can_view() {
		return current_user_can( 'edit_others_posts' );
	}
}

if ( ! function_exists( 'newsai_rest_get_insights' ) ) {
	function newsai_rest_get_insights( WP_REST_Request $request ) {
		if ( ! function_exists( 'newsai_insights_registry_payload' ) ) {
			return new WP_REST_Response( [ 'error' => 'registry_missing' ], 500 );
		}
		$days = (int) $request->get_param( 'days' );
		try {
			return new WP_REST_Response( newsai_insights_registry_payload( $days ), 200 );
		} catch ( \Throwable $e ) {
			return new WP_REST_Response(
				[
					'code'    => 'payload_error',
					'message' => $e->getMessage(),
				],
				500
			);
		}
	}
}

add_action( 'wp_ajax_newsai_insights_registry_get', 'newsai_ajax_insights_registry_get' );

if ( ! function_exists( 'newsai_ajax_insights_registry_get' ) ) {
	function newsai_ajax_insights_registry_get() {
		check_ajax_referer( 'newsai_ajax_nonce', 'nonce' );
		if ( ! current_user_can( 'edit_others_posts' ) ) {
			wp_send_json_error( [ 'message' => __( 'Forbidden.', 'newsroom-ai-assistant' ) ], 403 );
		}
		$days = isset( $_POST['days'] ) ? (int) wp_unslash( $_POST['days'] ) : 30;
		if ( ! function_exists( 'newsai_insights_registry_payload' ) ) {
			wp_send_json_error( [ 'message' => 'registry_missing' ], 500 );
		}
		try {
			wp_send_json_success( newsai_insights_registry_payload( $days ) );
		} catch ( \Throwable $e ) {
			wp_send_json_error( [ 'message' => $e->getMessage() ], 500 );
		}
	}
}
