<?php

declare(strict_types=1);

namespace FormConnector\API\Endpoints;

use FormConnector\API\Schema;
use FormConnector\Integration\CareHQ\Settings as CareHQSettings;

/**
 * CareHQ REST API endpoints.
 */
class CareHQEndpoints {

	private const NAMESPACE = 'fc/v1';

	/**
	 * Register CareHQ routes.
	 */
	public static function register(): void {
		register_rest_route(self::NAMESPACE, '/carehq/settings', [
			'methods' => \WP_REST_Server::READABLE,
			'callback' => [self::class, 'get_settings'],
			'permission_callback' => [self::class, 'permission_check'],
		]);

		register_rest_route(self::NAMESPACE, '/carehq/settings', [
			'methods' => \WP_REST_Server::CREATABLE,
			'callback' => [self::class, 'save_settings'],
			'permission_callback' => [self::class, 'permission_check'],
			'args' => [
				'account_id'       => Schema::text(),
				'api_key'          => Schema::text(),
				'api_secret'       => Schema::text(),
				'environment'      => Schema::enum(['production', 'staging', 'development']),
				'timeout'          => Schema::int(),
				'sales_channel_id' => Schema::text(),
			],
		]);

		register_rest_route(self::NAMESPACE, '/carehq/test', [
			'methods' => \WP_REST_Server::CREATABLE,
			'callback' => [self::class, 'test_connection'],
			'permission_callback' => [self::class, 'permission_check'],
			'args' => [
				'account_id'  => Schema::text(),
				'api_key'     => Schema::text(),
				'api_secret'  => Schema::text(),
				'environment' => Schema::enum(['production', 'staging', 'development']),
			],
		]);

		register_rest_route(self::NAMESPACE, '/carehq/clear', [
			'methods' => \WP_REST_Server::CREATABLE,
			'callback' => [self::class, 'clear_settings'],
			'permission_callback' => [self::class, 'permission_check'],
		]);

		register_rest_route(self::NAMESPACE, '/carehq/locations', [
			'methods' => \WP_REST_Server::READABLE,
			'callback' => [self::class, 'get_locations'],
			'permission_callback' => [self::class, 'permission_check'],
		]);

		register_rest_route(self::NAMESPACE, '/carehq/sales-channels', [
			'methods' => \WP_REST_Server::READABLE,
			'callback' => [self::class, 'get_sales_channels'],
			'permission_callback' => [self::class, 'permission_check'],
		]);

		register_rest_route(self::NAMESPACE, '/carehq/fields', [
			'methods' => \WP_REST_Server::READABLE,
			'callback' => [self::class, 'get_fields'],
			'permission_callback' => [self::class, 'permission_check'],
		]);
	}

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

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

	/**
	 * Save CareHQ API settings.
	 */
	public static function save_settings(\WP_REST_Request $request): \WP_REST_Response {
		$settings = new CareHQSettings();
		$result = $settings->save_settings([
			'account_id'       => $request->get_param('account_id'),
			'api_key'          => $request->get_param('api_key'),
			'api_secret'       => $request->get_param('api_secret'),
			'environment'      => $request->get_param('environment'),
			'timeout'          => $request->get_param('timeout'),
			'sales_channel_id' => $request->get_param('sales_channel_id'),
		]);

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

	/**
	 * Test CareHQ API connection.
	 */
	public static function test_connection(\WP_REST_Request $request): \WP_REST_Response {
		$settings = new CareHQSettings();
		
		// Check if credentials were provided in request (test before save)
		$credentials = null;
		if ($request->get_param('account_id')) {
			$credentials = [
				'account_id'  => $request->get_param('account_id'),
				'api_key'     => $request->get_param('api_key'),
				'api_secret'  => $request->get_param('api_secret'),
				'environment' => $request->get_param('environment'),
			];
		}

		$result = $settings->test_connection($credentials);
		$status = $result['success'] ? 200 : 400;
		
		return new \WP_REST_Response($result, $status);
	}

	/**
	 * Clear CareHQ API settings.
	 */
	public static function clear_settings(\WP_REST_Request $request): \WP_REST_Response {
		$settings = new CareHQSettings();
		$result = $settings->clear_settings();
		
		return new \WP_REST_Response($result, 200);
	}

	/**
	 * Get locations from CareHQ API.
	 */
	public static function get_locations(\WP_REST_Request $request): \WP_REST_Response {
		$api = \FormConnector\Integration\CareHQ\APIClient::get_instance();
		$force_refresh = (bool) $request->get_param('refresh');
		
		$result = $api->get_locations($force_refresh);
		
		if (is_wp_error($result)) {
			return new \WP_REST_Response([
				'success' => false,
				'error' => $result->get_error_code(),
				'message' => $result->get_error_message(),
			], 400);
		}

		// Transform to frontend format (APIClient returns raw items)
		$locations = [];
		foreach ($result as $item) {
			$locations[] = [
				'id' => $item['_id'] ?? '',
				'name' => $item['name'] ?? '',
			];
		}

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

	/**
	 * Get CareHQ standard fields.
	 */
	public static function get_fields(\WP_REST_Request $request): \WP_REST_Response {
		$manager = \FormConnector\Integration\Forms\FormIntegrationManager::get_instance();

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

	/**
	 * Get sales channels from CareHQ API.
	 */
	public static function get_sales_channels(\WP_REST_Request $request): \WP_REST_Response {
		$api = \FormConnector\Integration\CareHQ\APIClient::get_instance();
		$force_refresh = (bool) $request->get_param('refresh');
		
		$result = $api->get_sales_channels($force_refresh);
		
		if (is_wp_error($result)) {
			return new \WP_REST_Response([
				'success' => false,
				'error' => $result->get_error_code(),
				'message' => $result->get_error_message(),
			], 400);
		}

		// Transform to frontend format (APIClient returns raw items)
		$channels = [];
		foreach ($result as $item) {
			$channels[] = [
				'id' => $item['_id'] ?? '',
				'name' => $item['name'] ?? '',
			];
		}

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