<?php

namespace Waypoint\Agent\Rest\Handler;

use Waypoint\Agent\Dotenv\Manager;

class Rotate_Key {

	public function handle( \WP_REST_Request $request ): \WP_REST_Response|\WP_Error {
		$new_secret = $request->get_param( 'hmac_secret' );
		$path       = Manager::find_dotenv();

		if ( null === $path ) {
			return new \WP_Error(
				'waypoint_monitor_no_dotenv',
				'.env file not found — WAYPOINT_AGENT_KEY cannot be persisted on this server.',
				[ 'status' => 503 ]
			);
		}
		if ( ! is_writable( $path ) ) {
			return new \WP_Error(
				'waypoint_monitor_dotenv_not_writable',
				'.env file is not writable — cannot update WAYPOINT_AGENT_KEY.',
				[ 'status' => 503 ]
			);
		}

		$ok = Manager::set_key( $path, WAYPOINT_MONITOR_AGENT_KEY_NAME, $new_secret );
		if ( ! $ok ) {
			return new \WP_Error(
				'waypoint_monitor_write_failed',
				'Failed to write the new WAYPOINT_AGENT_KEY to .env — check server logs.',
				[ 'status' => 500 ]
			);
		}

		return rest_ensure_response( [
			'ok'         => true,
			'key_name'   => WAYPOINT_MONITOR_AGENT_KEY_NAME,
			'updated_at' => gmdate( 'c' ),
		] );
	}
}
