<?php
/**
 * Answyr — core REST routes.
 *
 * Currently just the provider connection test used by the settings page.
 *
 * @package Answyr
 */

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

final class Answyr_Core_Rest {

	private const NS = 'answyr/v1';

	public function register(): void {
		add_action( 'rest_api_init', array( $this, 'routes' ) );
	}

	public function routes(): void {
		register_rest_route(
			self::NS,
			'/test-connection',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'test_connection' ),
				'permission_callback' => static function () {
					return current_user_can( 'manage_options' );
				},
			)
		);
	}

	/**
	 * Verify a provider key. Uses the posted key if present, else the saved one,
	 * so "Test" works both before and after saving.
	 */
	public function test_connection( WP_REST_Request $request ) {
		$provider_id = sanitize_key( (string) $request->get_param( 'provider' ) );
		$provider    = Answyr_Provider_Registry::get( $provider_id );

		if ( ! $provider ) {
			return new WP_REST_Response(
				array(
					'ok'    => false,
					'error' => __( 'Unknown provider.', 'answyr' ),
				),
				400
			);
		}

		$key = trim( (string) $request->get_param( 'api_key' ) );
		if ( '' === $key ) {
			$key = Answyr_Settings::api_key( $provider_id );
		}
		if ( '' === $key ) {
			return new WP_REST_Response(
				array(
					'ok'    => false,
					'error' => __( 'No API key provided.', 'answyr' ),
				),
				400
			);
		}

		try {
			$ok = $provider->test_connection( $key );
		} catch ( \Throwable $e ) {
			return new WP_REST_Response(
				array(
					'ok'    => false,
					'error' => $e->getMessage(),
				),
				200
			);
		}

		return new WP_REST_Response(
			array(
				'ok'      => $ok,
				'message' => $ok
					? __( 'Connection OK.', 'answyr' )
					: __( 'Connection failed — check the key.', 'answyr' ),
			),
			200
		);
	}
}
