<?php
/**
 * Job Store.
 *
 * Transient-based session for the Execute tab. Holds:
 *   - The approval list (set of {source_post_id, orphan_url, phrase} tuples)
 *   - The progress state (cursor + per-row results)
 *
 * Job state is keyed by ID so the front-end can drive the batch via
 * repeated AJAX calls.
 *
 * @package Platform\Helm\Modules\Link_Architect
 */

declare( strict_types = 1 );

namespace Platform\Helm\Modules\Link_Architect;

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

final class JobStore {

	/**
	 * Save the user's approval list (called when they finish Tab 1).
	 *
	 * @param array<int,array{source_post_id:int,orphan_url:string,phrase:string}> $approvals
	 */
	public function save_approvals( int $user_id, array $approvals ): void {
		$key = LinkArchitectModule::APPROVAL_TRANSIENT . $user_id;
		set_transient( $key, $approvals, LinkArchitectModule::APPROVAL_TTL );
	}

	/**
	 * @return array<int,array{source_post_id:int,orphan_url:string,phrase:string}>
	 */
	public function get_approvals( int $user_id ): array {
		$key  = LinkArchitectModule::APPROVAL_TRANSIENT . $user_id;
		$data = get_transient( $key );
		return is_array( $data ) ? $data : [];
	}

	public function clear_approvals( int $user_id ): void {
		delete_transient( LinkArchitectModule::APPROVAL_TRANSIENT . $user_id );
	}

	/**
	 * Initialise an Execute job. Returns the job ID.
	 *
	 * @param array<int,array{source_post_id:int,orphan_url:string,phrase:string}> $approvals
	 */
	public function init_job( array $approvals ): string {
		$job_id = wp_generate_password( 16, false, false );
		$state  = [
			'approvals' => array_values( $approvals ),
			'cursor'    => 0,
			'total'     => count( $approvals ),
			'succeeded' => 0,
			'skipped'   => 0,
			'failed'    => 0,
			'log'       => [], // Last N entries of recent activity for UI feedback.
			'started'   => time(),
		];
		set_transient(
			LinkArchitectModule::JOB_TRANSIENT . $job_id,
			$state,
			LinkArchitectModule::JOB_TTL_SECONDS
		);
		return $job_id;
	}

	/**
	 * @return array<string,mixed>|null
	 */
	public function get_state( string $job_id ): ?array {
		$state = get_transient( LinkArchitectModule::JOB_TRANSIENT . $job_id );
		return is_array( $state ) ? $state : null;
	}

	/**
	 * @param array<string,mixed> $state
	 */
	public function save_state( string $job_id, array $state ): void {
		set_transient(
			LinkArchitectModule::JOB_TRANSIENT . $job_id,
			$state,
			LinkArchitectModule::JOB_TTL_SECONDS
		);
	}

	public function clear_job( string $job_id ): void {
		delete_transient( LinkArchitectModule::JOB_TRANSIENT . $job_id );
	}
}
