<?php
/**
 * GTM import-package REST controller.
 *
 * @package Carticy\Conversions\Rest
 */

declare(strict_types=1);

namespace Carticy\Conversions\Rest;

use Carticy\Conversions\Client\ClientTrackingSettings;
use Carticy\Conversions\Client\GtmImportBuilder;

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

/**
 * Serves the importable GTM container, built from the validated template with
 * the merchant's IDs filled in. It MUST come from {@see GtmImportBuilder} - never
 * the static `assets/gtm/carticy-conversions-gtm-v1.json` sample, which carries
 * placeholder IDs - so the import is a real, ready-to-use file (V1 guided import,
 * not auto-publish).
 */
final class GtmImportController extends AbstractRestController {

	/**
	 * GTM import builder.
	 *
	 * @var GtmImportBuilder
	 */
	private GtmImportBuilder $builder;

	/**
	 * Constructor.
	 *
	 * @param GtmImportBuilder $builder GTM import builder.
	 */
	public function __construct( GtmImportBuilder $builder ) {
		$this->builder = $builder;
	}

	/**
	 * Declared routes.
	 *
	 * @return array<int, array<string, mixed>>
	 */
	public function routes(): array {
		return array(
			array(
				'methods'  => 'GET',
				'route'    => '/gtm/import-package',
				'callback' => array( $this, 'get_package' ),
			),
		);
	}

	/**
	 * Build the import package from current settings.
	 *
	 * @return \WP_REST_Response
	 */
	public function get_package(): \WP_REST_Response {
		return $this->ok(
			array(
				'mode'      => 'guided_import',
				'container' => $this->builder->build( ClientTrackingSettings::from_options() ),
			)
		);
	}
}
