<?php
/**
 * Route handler for manual sync of cloud templates.
 *
 * @package    100Prints
 */

class Hundred_Prints_Route_Sync {

	/**
	 * Register routes.
	 */
	public function register_routes() {
		register_rest_route( '100prints/v1', '/sync-templates', [
			[
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => [ $this, 'sync_templates' ],
				'permission_callback' => [ $this, 'permission_check' ],
			],
		] );
	}

	/**
	 * Permission check callback.
	 */
	public function permission_check( $request ) {
		return current_user_can( 'manage_options' );
	}

	/**
	 * Trigger template sync.
	 */
	public function sync_templates( $request ) {
		$template_service = new Hundred_Prints_Template_Service();
		$result = $template_service->sync_cloud_templates();

		if ( isset( $result['error'] ) ) {
			return new WP_Error( '100prints_sync_failed', $result['error'], [ 'status' => 400 ] );
		}

		return rest_ensure_response( [
			'success' => true,
			'count'   => $result['count'],
		] );
	}
}
