<?php

namespace Waypoint\Agent\Cli;

use Waypoint\Agent\Base\Thing;
use Waypoint\Agent\Dotenv\Manager;

class Rotate_Key extends Thing {

	public function attach_hooks(): void {
		\WP_CLI::add_command( 'waypoint-agent rotate-key', [ $this, 'run' ] );
	}

	public function run( array $args, array $assoc_args ): void {
		$new_secret = bin2hex( random_bytes( 32 ) );
		$path       = Manager::find_dotenv();

		if ( null === $path || ! is_writable( $path ) ) {
			\WP_CLI::error( '.env file not found or not writable; cannot rotate WAYPOINT_AGENT_KEY.' );
		}

		$ok = Manager::set_key( $path, WAYPOINT_MONITOR_AGENT_KEY_NAME, $new_secret );
		if ( ! $ok ) {
			\WP_CLI::error( 'Failed to write WAYPOINT_AGENT_KEY to .env.' );
		}

		\WP_CLI::success( 'WAYPOINT_AGENT_KEY rotated.' );
		if ( isset( $assoc_args['show'] ) ) {
			\WP_CLI::line( 'New key: ' . $new_secret );
		}
	}
}
