<?php
/**
 * Bulk duplicate alt regeneration — Pro overlay only.
 *
 * Secure design (rafter-secure-design / auth):
 * - Identity: users who can generate alt text (edit_post on each attachment).
 * - AuthZ: This file is absent from the wordpress.org Lite zip. Lite can
 *   list duplicate groups but cannot run this pass. Overlay + license
 *   unlocks it. IDs are re-checked with current_user_can( 'edit_post' ).
 *
 * @package AIAltTextGenerator
 * @since 2.5.3
 */

namespace AIAltTextGenerator;

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

/**
 * Regenerates alt text for duplicate groups. Not loaded in Lite.
 *
 * @since 2.5.3
 */
final class PremiumDuplicateActions {

	/**
	 * @return array{queued: int, message: string}
	 */
	public static function regenerate(): array {
		if ( ! FeatureGate::isPro() ) {
			return [
				'queued'  => 0,
				'message' => __( 'Bulk duplicate regeneration is available in Pro.', 'wp-powersuite' ),
			];
		}

		$ids = array_values(
			array_filter(
				array_map( 'intval', DuplicateDetector::getDuplicateAttachmentIds() ),
				static function ( int $id ): bool {
					return $id > 0 && current_user_can( 'edit_post', $id );
				}
			)
		);
		if ( $ids === [] ) {
			return [
				'queued'  => 0,
				'message' => __( 'No duplicate alt images found.', 'wp-powersuite' ),
			];
		}

		$settings = Settings::get();
		if ( ! Settings::hasApiKey() ) {
			return [
				'queued'  => 0,
				'message' => __( 'API key is not configured for the selected provider.', 'wp-powersuite' ),
			];
		}

		if ( ! empty( $settings['queue_enabled'] ) ) {
			$added = Queue::enqueue( $ids, true );
			return [
				'queued'  => $added,
				'message' => sprintf(
					/* translators: %d: number of images */
					_n( '%d duplicate image queued for regeneration.', '%d duplicate images queued for regeneration.', $added, 'wp-powersuite' ),
					$added
				),
			];
		}

		$processed = 0;
		foreach ( array_slice( $ids, 0, 5 ) as $attachment_id ) {
			if ( ! Module::checkRateLimit() ) {
				break;
			}

			$result = GenerationService::generateForAttachment( (int) $attachment_id, true );
			if ( $result['status'] === 'success' ) {
				++$processed;
			}
		}

		return [
			'queued'  => $processed,
			'message' => sprintf(
				/* translators: 1: processed count, 2: total duplicates */
				__( 'Regenerated %1$d of %2$d duplicate images. Enable the background queue to process all at once.', 'wp-powersuite' ),
				$processed,
				count( $ids )
			),
		];
	}
}
