<?php
/**
 * REST endpoints for competitor import / migration.
 *
 * @package StoreSheet
 */

declare( strict_types=1 );

namespace StoreSheet\Rest;

defined( 'ABSPATH' ) || exit;

use StoreSheet\Importer\AdapterRegistry;
use StoreSheet\Importer\Importer;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

class ImportController {

	private const NAMESPACE = 'storesheet/v1';

	public function register_routes(): void {
		register_rest_route(
			self::NAMESPACE,
			'/import/sources',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_sources' ),
				'permission_callback' => array( $this, 'admin_permission' ),
			)
		);

		register_rest_route(
			self::NAMESPACE,
			'/import/apply',
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'apply' ),
				'permission_callback' => array( $this, 'admin_permission' ),
			)
		);

		register_rest_route(
			self::NAMESPACE,
			'/import/undo',
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'undo' ),
				'permission_callback' => array( $this, 'admin_permission' ),
			)
		);

		register_rest_route(
			self::NAMESPACE,
			'/import/deactivate-source',
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'deactivate_source' ),
				'permission_callback' => array( $this, 'admin_permission' ),
			)
		);
	}

	public function get_sources(): WP_REST_Response {
		return new WP_REST_Response( array( 'sources' => ( new Importer() )->sources() ), 200 );
	}

	public function apply( WP_REST_Request $request ): WP_REST_Response {
		$body      = (array) $request->get_json_params();
		$source_id = sanitize_key( $body['source_id'] ?? '' );

		$overrides = array(
			'settings' => is_array( $body['settings'] ?? null ) ? $body['settings'] : array(),
		);
		if ( is_array( $body['spreadsheet'] ?? null ) ) {
			$overrides['spreadsheet'] = $body['spreadsheet'];
		}
		$flags = array(
			'adopt_sheet'      => ! empty( $body['adopt_sheet'] ),
			'deactivate_after' => ! empty( $body['deactivate_after'] ),
		);

		$report = ( new Importer() )->apply( $source_id, $overrides, $flags );

		if ( $flags['deactivate_after'] ) {
			$this->do_deactivate( $source_id );
		}

		return new WP_REST_Response( $report, 200 );
	}

	public function undo(): WP_REST_Response {
		return new WP_REST_Response( array( 'restored' => ( new Importer() )->undo() ), 200 );
	}

	public function deactivate_source( WP_REST_Request $request ): WP_REST_Response {
		$body      = (array) $request->get_json_params();
		$source_id = sanitize_key( $body['source_id'] ?? '' );
		$ok        = $this->do_deactivate( $source_id );
		if ( ! $ok ) {
			return new WP_REST_Response( array( 'message' => __( 'Unknown migration source.', 'storesheet' ) ), 400 );
		}
		return new WP_REST_Response( array( 'deactivated' => true ), 200 );
	}

	/**
	 * Deactivate ONLY the plugin files a known adapter declares — never an
	 * arbitrary, caller-supplied path.
	 */
	private function do_deactivate( string $source_id ): bool {
		$adapter = ( new AdapterRegistry() )->get( $source_id );
		if ( null === $adapter ) {
			return false;
		}
		$files = $adapter->plugin_files();
		if ( empty( $files ) ) {
			return false;
		}
		if ( ! function_exists( 'deactivate_plugins' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}
		deactivate_plugins( $files );
		return true;
	}

	public function admin_permission(): bool {
		return current_user_can( 'manage_woocommerce' );
	}
}
