<?php
/**
 * @package Hafenstudios\Kurato
 */

namespace Hafenstudios\Kurato\Cockpit\Rest;

use Hafenstudios\Kurato\Cockpit\AgentSync;
use Hafenstudios\Kurato\Cockpit\SignatureGuard;

defined( 'ABSPATH' ) || exit;

/**
 * POST kurato-cockpit/v1/agents/sync - Agent anlegen/aendern/sperren.
 *
 * Server-signiert, idempotent ueber agent_id. Legt den Schattennutzer an bzw.
 * setzt ihn inaktiv (AgentSync + ShadowUserStore). Der Replay-Schutz sitzt in
 * der Signaturpruefung (Nonce-Transient).
 */
final class AgentsSyncController {

	public const REST_NAMESPACE = 'kurato-cockpit/v1';

	private SignatureGuard $guard;

	private AgentSync $sync;

	/**
	 * @param SignatureGuard $guard Server-Signatur-Pruefung.
	 * @param AgentSync      $sync  Schattennutzer-Synchronisation.
	 */
	public function __construct( SignatureGuard $guard, AgentSync $sync ) {
		$this->guard = $guard;
		$this->sync  = $sync;
	}

	/**
	 * @return void
	 */
	public function register_routes(): void {
		register_rest_route(
			self::REST_NAMESPACE,
			'/agents/sync',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'sync' ),
				'permission_callback' => array( $this->guard, 'permission' ),
			)
		);
	}

	/**
	 * @param \WP_REST_Request $request Request.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public function sync( \WP_REST_Request $request ) {
		$agent_id = (string) $request->get_param( 'agent_id' );
		$result   = $this->sync->apply(
			$agent_id,
			array(
				'email'  => (string) $request->get_param( 'email' ),
				'name'   => (string) $request->get_param( 'name' ),
				'status' => (string) $request->get_param( 'status' ),
			)
		);

		if ( empty( $result['ok'] ) ) {
			return new \WP_Error(
				'invalid_agent',
				__( 'Die Agent-Angaben waren unvollstaendig. Naechster Schritt: agent_id muss gesetzt sein.', 'kurato' ),
				array( 'status' => 400 )
			);
		}

		return new \WP_REST_Response(
			array(
				'ok'         => true,
				'wp_user_id' => (int) ( $result['wp_user_id'] ?? 0 ),
				'created'    => (bool) ( $result['created'] ?? false ),
			),
			200
		);
	}
}
