<?php
/**
 * Best-effort adapter: scans wp_options for Google-Sheets-shaped config so a
 * competitor with no dedicated adapter can still be partially imported. Nothing
 * it finds is auto-applied — the user confirms every mapping in the wizard.
 *
 * @package StoreSheet
 */

declare( strict_types=1 );

namespace StoreSheet\Importer\Adapters;

defined( 'ABSPATH' ) || exit;

use StoreSheet\Importer\ImportPlan;
use StoreSheet\Importer\SourceAdapter;

final class GenericAdapter implements SourceAdapter {

	private const KEY_PATTERNS = array( 'gsheet', 'google_sheet', 'googlesheet', 'spreadsheet' );

	public function id(): string {
		return 'generic';
	}

	public function label(): string {
		return __( 'Other Google Sheets plugin (scan)', 'storesheet' );
	}

	public function plugin_files(): array {
		return array();
	}

	public function is_present(): bool {
		return ! empty( $this->candidate_options() );
	}

	public function read_config(): ImportPlan {
		$candidates  = $this->candidate_options();
		$spreadsheet = null;
		$mappings    = array();

		foreach ( $candidates as $name => $value ) {
			$mappings[] = array(
				'column' => $name,
				'target' => '',
			);
			if ( null === $spreadsheet && is_string( $value ) ) {
				$id = $this->extract_spreadsheet_id( $value );
				if ( '' !== $id ) {
					$spreadsheet = array(
						'id'  => $id,
						'url' => 'https://docs.google.com/spreadsheets/d/' . $id . '/edit',
					);
				}
			}
		}

		return new ImportPlan(
			$this->id(),
			$this->label(),
			null,
			$spreadsheet,
			array(),
			$mappings,
			array( __( 'Auto-detected settings from another plugin. Review and map each field before applying — nothing is imported until you confirm.', 'storesheet' ) )
		);
	}

	public function supports_sheet_adopt(): bool {
		return true;
	}

	/**
	 * Options whose name matches a Sheets-ish pattern. Reads option names from the
	 * options table directly (autoload-safe) and filters by pattern.
	 *
	 * @return array<string,mixed>
	 */
	private function candidate_options(): array {
		global $wpdb;

		$like = array();
		$args = array();
		foreach ( self::KEY_PATTERNS as $p ) {
			$like[] = 'option_name LIKE %s';
			$args[] = '%' . $wpdb->esc_like( $p ) . '%';
		}
		$sql = "SELECT option_name FROM {$wpdb->options} WHERE " . implode( ' OR ', $like ) . ' LIMIT 100'; // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared

		$names = $wpdb->get_col( $wpdb->prepare( $sql, $args ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.NotPrepared

		$out = array();
		foreach ( (array) $names as $name ) {
			// Never surface our own options as a migration source.
			if ( 0 === strpos( (string) $name, 'storesheet' ) ) {
				continue;
			}
			$out[ $name ] = get_option( $name );
		}
		return $out;
	}

	private function extract_spreadsheet_id( string $input ): string {
		if ( preg_match( '#/spreadsheets/d/([a-zA-Z0-9_-]+)#', $input, $m ) ) {
			return $m[1];
		}
		if ( preg_match( '/^[a-zA-Z0-9_-]{20,}$/', $input ) ) {
			return $input;
		}
		return '';
	}
}
