<?php

namespace WeDevs\AppBridge\Core\REST;

use WeDevs\AppBridge\Core\Contracts\SettingsSchemaInterface;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

abstract class AbstractSettingsController extends BaseController {

	protected $base = 'settings';

	/**
	 * Return the settings schema for this integration.
	 */
	abstract protected function schema(): SettingsSchemaInterface;

	public function register_routes(): void {
		register_rest_route(
			$this->namespace,
			'/' . $this->base . '/schema',
			[
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => fn() => rest_ensure_response( $this->schema()->get_schema() ),
				'permission_callback' => fn() => $this->check_manage_options(),
			]
		);

		register_rest_route(
			$this->namespace,
			'/' . $this->base,
			[
				[
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => fn() => rest_ensure_response( get_option( $this->schema()->get_option_key(), [] ) ),
					'permission_callback' => fn() => $this->check_manage_options(),
				],
				[
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => [ $this, 'save' ],
					'permission_callback' => fn() => $this->check_manage_options(),
				],
			]
		);
	}

	public function save( WP_REST_Request $request ): WP_REST_Response {
		$this->schema()->save( $request->get_params() );

		return rest_ensure_response( $this->schema()->get_schema() );
	}
}
