<?php

declare(strict_types=1);

namespace SecurWP\Modules\Cloud\Services;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use SecurWP\Modules\Cloud\SecureApi;
use SecurWP\Modules\Cloud\Service\CloudSettings;

/**
 * CommandAckService - Sends command execution acknowledgements to Console.
 */
	class CommandAckService {

	/**
	 * Send an ACK for a command directly to Console.
	 *
	 * @param string               $command_id  The command UUID.
	 * @param string               $status      running|succeeded|failed
	 * @param array<string,mixed>  $result      Command execution result.
	 * @param string|null          $error       Error message if failed.
	 * @param string|null          $error_code  Structured error code.
	 * @return bool True if Console accepted the ACK.
	 */
	public static function send(
		string $command_id,
		string $status,
		array $result = [],
		?string $error = null,
		?string $error_code = null
	): bool {
		$settings = CloudSettings::get_all();
		if ( empty( $settings['site_token'] ) || empty( $settings['site_secret'] ) ) {
			return false;
		}
		$migration_status = strtolower( trim( (string) ( $settings['migration_status'] ?? 'none' ) ) );
		if ( $migration_status !== '' && $migration_status !== 'none' ) {
			return false;
		}

		$api = new SecureApi(
			$settings['license_key'] ?? '',
			$settings['site_token'] ?? '',
			$settings['site_secret'] ?? ''
		);
		$result_payload = empty( $result ) ? (object) [] : $result;

		$payload = [
			'command_id'       => $command_id,
			'status'           => $status,
			'result'           => $result_payload,
			'error'            => $error,
			'error_code'       => $error_code,
			'executor_version' => CommandExecutor::VERSION,
		];

		$response = $api->post_control_plane( 'services/commands/ack', $payload );

		return (bool) $response;
		}

	/**
	 * Send "running" status to indicate the command has started execution.
	 *
	 * @param string $command_id
	 * @return bool
	 */
		public static function running( string $command_id ): bool {
			return self::send( $command_id, 'running' );
		}

	/**
	 * Send "succeeded" status with result.
	 *
	 * @param string              $command_id
	 * @param array<string,mixed> $result
	 * @return bool
	 */
		public static function succeeded( string $command_id, array $result = [] ): bool {
			return self::send( $command_id, 'succeeded', $result );
		}

	/**
	 * Send "failed" status with error details.
	 *
	 * @param string      $command_id
	 * @param string      $error
	 * @param string|null $error_code
	 * @param array       $result
	 * @return bool
	 */
		public static function failed( string $command_id, string $error, ?string $error_code = null, array $result = [] ): bool {
			return self::send( $command_id, 'failed', $result, $error, $error_code );
		}
	}
