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

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

add_action( 'rest_api_init', 'newsai_register_settings_rest_routes' );

if ( ! function_exists( 'newsai_register_settings_rest_routes' ) ) {
	function newsai_register_settings_rest_routes() {
		register_rest_route(
			'newsroom-os/v1',
			'/settings',
			[
				[
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => 'newsai_rest_get_settings',
					'permission_callback' => 'newsai_rest_settings_can_manage',
				],
				[
					'methods'             => WP_REST_Server::EDITABLE,
					'callback'            => 'newsai_rest_patch_settings',
					'permission_callback' => 'newsai_rest_settings_can_manage',
					'args'                => [
						'section' => [
							'required'          => true,
							'type'              => 'string',
							'sanitize_callback' => 'sanitize_key',
						],
						'data'    => [
							'required' => true,
							'type'     => 'object',
						],
					],
				],
			]
		);
		register_rest_route(
			'newsroom-os/v1',
			'/settings/action',
			[
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => 'newsai_rest_settings_action',
				'permission_callback' => 'newsai_rest_settings_can_manage',
				'args'                => [
					'action' => [
						'required'          => true,
						'type'              => 'string',
						'sanitize_callback' => 'sanitize_key',
					],
					'params' => [
						'type' => 'object',
					],
				],
			]
		);
		register_rest_route(
			'newsroom-os/v1',
			'/settings/meta',
			[
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => 'newsai_rest_get_settings_meta',
				'permission_callback' => 'newsai_rest_settings_can_manage',
			]
		);
	}
}

if ( ! function_exists( 'newsai_rest_get_settings_meta' ) ) {
	function newsai_rest_get_settings_meta() {
		return new WP_REST_Response( newsai_settings_registry_meta(), 200 );
	}
}

if ( ! function_exists( 'newsai_rest_settings_action' ) ) {
	function newsai_rest_settings_action( WP_REST_Request $request ) {
		$action = (string) $request->get_param( 'action' );
		$params = $request->get_param( 'params' );
		if ( ! is_array( $params ) ) {
			$params = [];
		}
		$result = newsai_settings_registry_run_action( $action, $params );
		if ( is_wp_error( $result ) ) {
			return $result;
		}
		return new WP_REST_Response(
			array_merge(
				$result,
				[
					'values'   => newsai_settings_registry_read_values(),
					'health'   => newsai_settings_registry_health(),
					'profiles' => [
						'site'      => (string) get_option( 'newsai_site_profile', 'newsroom' ),
						'publisher' => function_exists( 'newsai_get_publisher_profile' ) ? newsai_get_publisher_profile() : 'standard',
					],
					'meta'     => newsai_settings_registry_meta(),
				]
			),
			200
		);
	}
}

add_action( 'wp_ajax_newsai_settings_registry_meta', 'newsai_ajax_settings_registry_meta' );

if ( ! function_exists( 'newsai_ajax_settings_registry_meta' ) ) {
	function newsai_ajax_settings_registry_meta() {
		newsai_ajax_settings_registry_verify();
		wp_send_json_success( newsai_settings_registry_meta() );
	}
}

if ( ! function_exists( 'newsai_rest_settings_can_manage' ) ) {
	function newsai_rest_settings_can_manage() {
		return current_user_can( 'manage_options' );
	}
}

if ( ! function_exists( 'newsai_rest_get_settings' ) ) {
	/**
	 * @return WP_REST_Response
	 */
	function newsai_rest_get_settings() {
		if ( ! function_exists( 'newsai_settings_registry_payload' ) ) {
			return new WP_REST_Response( [ 'error' => 'registry_missing' ], 500 );
		}
		return new WP_REST_Response( newsai_settings_registry_payload(), 200 );
	}
}

add_action( 'wp_ajax_newsai_settings_registry_get', 'newsai_ajax_settings_registry_get' );
add_action( 'wp_ajax_newsai_settings_registry_patch', 'newsai_ajax_settings_registry_patch' );

if ( ! function_exists( 'newsai_ajax_settings_registry_verify' ) ) {
	function newsai_ajax_settings_registry_verify() {
		check_ajax_referer( 'newsai_ajax_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Forbidden.', 'newsroom-ai-assistant' ) ], 403 );
		}
	}
}

if ( ! function_exists( 'newsai_ajax_settings_registry_get' ) ) {
	function newsai_ajax_settings_registry_get() {
		newsai_ajax_settings_registry_verify();
		if ( ! function_exists( 'newsai_settings_registry_payload' ) ) {
			wp_send_json_error( [ 'message' => 'registry_missing' ], 500 );
		}
		wp_send_json_success( newsai_settings_registry_payload() );
	}
}

if ( ! function_exists( 'newsai_ajax_settings_registry_patch' ) ) {
	function newsai_ajax_settings_registry_patch() {
		newsai_ajax_settings_registry_verify();
		$section = isset( $_POST['section'] ) ? sanitize_key( wp_unslash( (string) $_POST['section'] ) ) : '';
		$raw     = isset( $_POST['data'] ) ? wp_unslash( $_POST['data'] ) : '';
		$data    = is_string( $raw ) ? json_decode( $raw, true ) : $raw;
		if ( ! is_array( $data ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid section data.', 'newsroom-ai-assistant' ) ], 400 );
		}
		$result = newsai_settings_registry_save_section( $section, $data );
		if ( is_wp_error( $result ) ) {
			wp_send_json_error(
				[
					'message' => $result->get_error_message(),
					'code'    => $result->get_error_code(),
				],
				400
			);
		}
		wp_send_json_success(
			[
				'ok'     => true,
				'values' => newsai_settings_registry_read_values( [ $section ] ),
				'health' => newsai_settings_registry_health(),
			]
		);
	}
}

add_action( 'wp_ajax_newsai_settings_registry_action', 'newsai_ajax_settings_registry_action' );

if ( ! function_exists( 'newsai_ajax_settings_registry_action' ) ) {
	function newsai_ajax_settings_registry_action() {
		newsai_ajax_settings_registry_verify();
		$action = isset( $_POST['settings_action'] ) ? sanitize_key( wp_unslash( (string) $_POST['settings_action'] ) ) : '';
		$params = isset( $_POST['params'] ) ? wp_unslash( $_POST['params'] ) : '';
		$decoded = is_string( $params ) ? json_decode( $params, true ) : $params;
		if ( ! is_array( $decoded ) ) {
			$decoded = [];
		}
		$result = newsai_settings_registry_run_action( $action, $decoded );
		if ( is_wp_error( $result ) ) {
			wp_send_json_error( [ 'message' => $result->get_error_message() ], 400 );
		}
		wp_send_json_success(
			array_merge(
				$result,
				[
					'values'   => newsai_settings_registry_read_values(),
					'health'   => newsai_settings_registry_health(),
					'profiles' => [
						'site'      => (string) get_option( 'newsai_site_profile', 'newsroom' ),
						'publisher' => function_exists( 'newsai_get_publisher_profile' ) ? newsai_get_publisher_profile() : 'standard',
					],
					'meta'     => newsai_settings_registry_meta(),
				]
			)
		);
	}
}

if ( ! function_exists( 'newsai_rest_patch_settings' ) ) {
	/**
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response|WP_Error
	 */
	function newsai_rest_patch_settings( WP_REST_Request $request ) {
		$section = (string) $request->get_param( 'section' );
		$data    = $request->get_param( 'data' );
		if ( ! is_array( $data ) ) {
			return new WP_Error( 'invalid_data', __( 'Invalid section data.', 'newsroom-ai-assistant' ), [ 'status' => 400 ] );
		}
		$result = newsai_settings_registry_save_section( $section, $data );
		if ( is_wp_error( $result ) ) {
			return $result;
		}
		return new WP_REST_Response(
			[
				'ok'     => true,
				'values' => newsai_settings_registry_read_values( [ $section ] ),
				'health' => newsai_settings_registry_health(),
			],
			200
		);
	}
}
