<?php
/**
 * Stepper Handler
 *
 * Encapsulates business logic for step updates and mapping saves.
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/includes/common/handlers
 */

declare(strict_types=1);

namespace MOMCS_Sync\Includes\Common\Handlers;

use MOMCS_Sync\Includes\Common\Models\Multichannels_Model;
use MOMCS_Sync\Includes\Common\Constants\Plugin_Constants;

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

/**
 * Class Stepper_Handler
 */
class Stepper_Handler {
	/**
	 * Channels model.
	 *
	 * @var Multichannels_Model
	 */
	private Multichannels_Model $multichannels_model;

	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->multichannels_model = new Multichannels_Model();
	}

	/**
	 * Update current step for a marketplace or a specific channel.
	 *
	 * @param string      $marketplace  Marketplace slug.
	 * @param int         $step         Step value.
	 * @param string|null $channel_uuid Optional channel UUID to scope the update.
	 *
	 * @throws \RuntimeException When DB update fails.
	 * @return void
	 */
	public function update_step( string $marketplace, int $step, ?string $channel_uuid = null ): void {
		if ( $channel_uuid ) {
			$result = $this->multichannels_model->update_current_step( $channel_uuid, $step );
		} else {
			$result = $this->multichannels_model->update_marketplace_current_step( $marketplace, $step );
		}

		if ( false === $result || 0 === (int) $result ) {
			throw new \RuntimeException( esc_html( Plugin_Constants::MESSAGE_FAILED_TO_UPDATE_STEP ) );
		}
	}
}
