<?php

/**
 * Shared storage for pending (awaiting-confirmation) tool actions.
 *
 * Single source of truth for the transient format used by both the synchronous
 * chat confirmation flow (Controller) and the async Plugin Builder worker, so a
 * confirmation created in either place is consumable by handleConfirmToolAction.
 *
 * @package LolaCore\Chat
 * @license GPL-2.0-or-later
 */

declare(strict_types=1);

namespace LolaCore\Chat;

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

final class PendingActionStore {

	private const PREFIX = 'lolacore_pending_action_';

	/**
	 * Store a batch of pending tool actions awaiting user confirmation.
	 *
	 * @param string                            $actionId   Unique confirmation id.
	 * @param string                            $sessionId  Chat session id (may be '' for async jobs;
	 *                                                       the approve request supplies the live session id).
	 * @param array<int, array<string, mixed>>  $batchItems Items, each with tool_name, params, preview_cache_key, etc.
	 */
	public static function storeBatch( string $actionId, string $sessionId, array $batchItems ): void {
		\set_transient(
			self::PREFIX . $actionId,
			array(
				'session_id'  => $sessionId,
				'batch_items' => $batchItems,
				'created_at'  => time(),
			),
			2 * HOUR_IN_SECONDS
		);
	}

	/**
	 * @return array<string, mixed>|null
	 */
	public static function get( string $actionId ): ?array {
		$data = \get_transient( self::PREFIX . $actionId );

		return is_array( $data ) ? $data : null;
	}

	public static function delete( string $actionId ): void {
		\delete_transient( self::PREFIX . $actionId );
	}
}
