<?php

declare(strict_types=1);

namespace Australcode\Rewards\Cli;

use Australcode\Rewards\Service\Import\YithImporter;

defined( 'ABSPATH' ) || exit;

/**
 * `wp acrwd import <source>` — migrate point balances from another loyalty
 * plugin into Australcode Points and Rewards. Registered only under WP-CLI.
 */
final class ImportCommand {

	public function __construct(
		private readonly YithImporter $yith,
	) {
	}

	/**
	 * Imports point balances from YITH WooCommerce Points and Rewards.
	 *
	 * Reads each user's authoritative YITH balance and lifetime totals and
	 * writes them into this plugin's wallet, with one opening ledger entry per
	 * user. Idempotent: already-imported users are skipped on re-runs.
	 *
	 * ## OPTIONS
	 *
	 * [--dry-run]
	 * : Report what would be imported without writing anything.
	 *
	 * ## EXAMPLES
	 *
	 *     # Preview the migration
	 *     wp acrwd import yith --dry-run
	 *
	 *     # Run it
	 *     wp acrwd import yith
	 *
	 * @when after_wp_load
	 *
	 * @param array<int,string>    $args       Positional arguments (unused).
	 * @param array<string,string> $assoc_args Associative arguments.
	 */
	public function yith( array $args, array $assoc_args ): void {
		$dry_run = isset( $assoc_args['dry-run'] );
		$report  = $this->yith->run( $dry_run );

		\WP_CLI::log(
			sprintf(
				'Candidates: %d | already imported: %d | eligible: %d | points: %d',
				$report->candidates,
				$report->already_imported,
				$report->eligible,
				$report->points
			)
		);

		if ( $dry_run ) {
			\WP_CLI::success(
				sprintf( 'Dry run — no changes written. %d user(s) would be imported.', $report->eligible )
			);
			return;
		}

		\WP_CLI::success(
			sprintf( 'Imported %d user(s) (%d points).', $report->imported, $report->points )
		);
	}
}
