<?php

namespace Fotogenic_AI;

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

/**
 * Creates and validates the upstream identity for one billable request.
 */
final class Upstream_Request_Identity {
	private const BYTE_LENGTH = 32;

	private function __construct() {}

	/**
	 * @param callable|null $random_source Optional secure byte source for deterministic tests.
	 * @return string|\WP_Error
	 */
	public static function create( ?callable $random_source = null ) {
		$random_source = $random_source ?? 'random_bytes';
		try {
			$bytes = $random_source( self::BYTE_LENGTH );
		} catch ( \Throwable $error ) {
			unset( $error );
			return self::unavailable_error();
		}

		if ( ! is_string( $bytes ) || self::BYTE_LENGTH !== strlen( $bytes ) ) {
			return self::unavailable_error();
		}

		return bin2hex( $bytes );
	}

	public static function is_valid( string $key ): bool {
		return 1 === preg_match( '/\A[a-f0-9]{64}\z/D', $key );
	}

	private static function unavailable_error(): \WP_Error {
		return new \WP_Error(
			'fotogenic_ai_upstream_identity_unavailable',
			__( 'A secure generation request identity could not be created. Please try again.', 'fotogenic-ai' ),
			[
				'status'         => 503,
				'not_dispatched' => true,
			]
		);
	}
}
