<?php
/**
 * Adapter for "FlexStock – Stock Sync with Google Sheet" (WPPOOL).
 *
 * Option shapes below were confirmed against the free plugin's source
 * (stock-sync-with-google-sheet-for-woocommerce, v3.17.0 at audit time; see
 * .superpowers/sdd/competitor-flexstock.md):
 *  - `ssgsw_spreadsheet_id` holds the parsed, bare Google Spreadsheet ID
 *    (derived server-side from the pasted URL via regex,
 *    includes/classes/class-hooks.php:1243-1261), used directly in Sheets API
 *    calls. `ssgsw_spreadsheet_url` holds the raw pasted URL as a
 *    fallback/display value. As with FlexOrder, nearly every `ssgsw_*` option
 *    row is pre-seeded empty on every plugin bootstrap
 *    (`App::reset_options()`, includes/classes/class-app.php:478-489), so
 *    only a non-empty `spreadsheet_id` is a real "configured" signal.
 *  - This plugin syncs WooCommerce Products (stock, price, attributes, etc.)
 *    — there is no separate stock resource in StoreSheet's schema, so this
 *    maps to `sync_products`. Confirmed no order-status filter option exists
 *    anywhere (orders are only read to recompute a "total sales" column).
 *  - Sync direction is genuinely bidirectional and configurable
 *    (`ssgsw_selected_sync_mode` / `ssgsw_live_sync_direction`, defaulting to
 *    `'bidirectional'`) — unlike StoreSheet free's WC → Sheets-only push, so
 *    the adapter warns about this mismatch explicitly.
 *  - `ssgsw_credentials` stores the merchant's own uploaded Google
 *    service-account JSON (as a JSON-encoded string; private RSA key
 *    included), used for a JWT-bearer 2-legged auth flow — structurally
 *    incompatible with StoreSheet's user-consent OAuth `GoogleOAuthClient`. It
 *    is never read here; the user reconnects Google through StoreSheet's own
 *    flow instead.
 *
 * @package StoreSheet
 */

declare( strict_types=1 );

namespace StoreSheet\Importer\Adapters;

defined( 'ABSPATH' ) || exit;

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

final class FlexStockAdapter implements SourceAdapter {

	private const OPTION_SPREADSHEET_ID  = 'ssgsw_spreadsheet_id';
	private const OPTION_SPREADSHEET_URL = 'ssgsw_spreadsheet_url';

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

	public function label(): string {
		return __( 'FlexStock – Stock Sync with Google Sheet', 'storesheet' );
	}

	public function plugin_files(): array {
		return array( 'stock-sync-with-google-sheet-for-woocommerce/stock-sync-with-google-sheet-for-woocommerce.php' );
	}

	public function is_present(): bool {
		if ( ! function_exists( 'is_plugin_active' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}
		foreach ( $this->plugin_files() as $file ) {
			if ( is_plugin_active( $file ) ) {
				return true;
			}
		}
		return '' !== (string) get_option( self::OPTION_SPREADSHEET_ID, '' );
	}

	public function read_config(): ImportPlan {
		$warnings = array();

		$spreadsheet    = null;
		$spreadsheet_id = (string) get_option( self::OPTION_SPREADSHEET_ID, '' );
		if ( '' !== $spreadsheet_id ) {
			$raw_url     = (string) get_option( self::OPTION_SPREADSHEET_URL, '' );
			$spreadsheet = array(
				'id'  => $spreadsheet_id,
				'url' => '' !== $raw_url ? $raw_url : 'https://docs.google.com/spreadsheets/d/' . $spreadsheet_id . '/edit',
			);
		}

		// Stock is a product-level attribute in StoreSheet's schema — there is
		// no standalone stock resource, so a present FlexStock config always
		// maps to sync_products.
		$settings = array_filter(
			array(
				'sync_products' => true,
			),
			static function ( $v ) {
				return null !== $v;
			}
		);

		// FlexStock stores its own Google service-account key for direct,
		// JWT-signed Sheets API access — never a client secret StoreSheet's
		// OAuth flow could reuse. See class doc block above.
		$credentials = null;
		$warnings[]  = __( 'FlexStock stores its own Google service-account key for direct Sheets API access — this can\'t be reused by StoreSheet\'s OAuth connection; connect your Google account on the next step.', 'storesheet' );
		$warnings[]  = __( 'FlexStock syncs stock bi-directionally between WooCommerce and Google Sheets; StoreSheet\'s free build only pushes WooCommerce → Sheets.', 'storesheet' );

		return new ImportPlan( $this->id(), $this->label(), $credentials, $spreadsheet, $settings, array(), $warnings );
	}

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