<?php

declare(strict_types=1);

namespace FormConnector\API\Endpoints;

use FormConnector\Integration\AI\AIMapper;
use FormConnector\Integration\Forms\FormIntegrationManager;
use FormConnector\Integration\Forms\SubmissionHandler;

/**
 * AI Mapping REST API endpoints.
 *
 * Provides AI-powered field mapping suggestions via the FormConnector
 * backend server (app.formconnector.co.uk). Only field metadata is
 * sent — no submission data or PII.
 */
class AIEndpoints {

	private const NAMESPACE = 'fc/v1';

	/**
	 * Register AI routes.
	 */
	public static function register(): void {
		register_rest_route(self::NAMESPACE, '/ai/suggest-mappings', [
			'methods'             => \WP_REST_Server::CREATABLE,
			'callback'            => [self::class, 'suggest_mappings'],
			'permission_callback' => [self::class, 'permission_check'],
		]);

		register_rest_route(self::NAMESPACE, '/ai/test-connection', [
			'methods'             => \WP_REST_Server::CREATABLE,
			'callback'            => [self::class, 'test_connection'],
			'permission_callback' => [self::class, 'permission_check'],
		]);

		register_rest_route(self::NAMESPACE, '/ai/settings', [
			'methods'             => \WP_REST_Server::READABLE,
			'callback'            => [self::class, 'get_settings'],
			'permission_callback' => [self::class, 'permission_check'],
		]);

		register_rest_route(self::NAMESPACE, '/ai/settings', [
			'methods'             => \WP_REST_Server::CREATABLE,
			'callback'            => [self::class, 'save_settings'],
			'permission_callback' => [self::class, 'permission_check'],
		]);
	}

	/**
	 * Permission check for admin-only endpoints.
	 */
	public static function permission_check(): bool {
		return current_user_can('manage_options');
	}

	/**
	 * Generate AI mapping suggestions for a form.
	 */
	public static function suggest_mappings(\WP_REST_Request $request): \WP_REST_Response {
		$plugin  = sanitize_text_field($request->get_param('form_plugin') ?? '');
		$form_id = sanitize_text_field($request->get_param('form_id') ?? '');

		if (empty($plugin) || empty($form_id)) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => __('form_plugin and form_id are required.', 'form-connector'),
			], 400);
		}

		// Load form fields via the form adapter
		$manager     = FormIntegrationManager::get_instance();
		$form_fields = $manager->get_form_fields($plugin, $form_id);

		if (empty($form_fields)) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => __('No form fields found for the specified form.', 'form-connector'),
			], 404);
		}

		// Get CareHQ target fields
		$carehq_fields = self::get_carehq_fields();

		// Call AIMapper
		$result = AIMapper::suggest($form_fields, $carehq_fields);

		if (is_wp_error($result)) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => $result->get_error_message(),
				'error'   => $result->get_error_code(),
			], 400);
		}

		return new \WP_REST_Response([
			'success' => true,
			'data'    => $result,
		], 200);
	}

	/**
	 * Test the AI provider connection.
	 */
	public static function test_connection(\WP_REST_Request $request): \WP_REST_Response {
		$result = AIMapper::test_connection();

		return new \WP_REST_Response([
			'success' => $result['success'],
			'message' => $result['message'],
			'data'    => $result,
		], $result['success'] ? 200 : 400);
	}

	/**
	 * Get AI settings.
	 */
	public static function get_settings(\WP_REST_Request $request): \WP_REST_Response {
		return new \WP_REST_Response([
			'success' => true,
			'data'    => AIMapper::get_settings(),
		], 200);
	}

	/**
	 * Save AI settings.
	 */
	public static function save_settings(\WP_REST_Request $request): \WP_REST_Response {
		$data = $request->get_json_params();

		if (empty($data)) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => __('No settings provided.', 'form-connector'),
			], 400);
		}

		$result = AIMapper::save_settings($data);

		return new \WP_REST_Response($result, 200);
	}

	/**
	 * Get the CareHQ standard fields.
	 * Uses the same field list as SubmissionHandler.
	 */
	private static function get_carehq_fields(): array {
		return [
			'first_name'        => 'First Name',
			'last_name'         => 'Last Name',
			'email'             => 'Email Address',
			'phone'             => 'Phone Number',
			'care_requirements' => 'Message / Enquiry Details',
		];
	}
}
