<?php

class Simplyin_Env {


	/**
	 * @return array<string, string>
	 */
	public static function read(): array {
		return self::get_default();
	}

	/**
	 * Safe default for a local/unconfigured checkout: only the prod backend is
	 * populated, matching the same prod fallback simplyin.php already applies when
	 * APP_ENV is unset. A real deploy overwrites APP_ENV plus the single
	 * BACKEND_ENVIRONMENT_* key matching the branch being built (the other three
	 * stay at their empty/default values) via .github/workflows/azure-deploy.yml,
	 * sourced from GH Actions repo variables — the dev/stage/preprod hostnames are
	 * never committed here.
	 *
	 * @return array<string, string>
	 */
	private static function get_default(): array {
		return [
			'BACKEND_ENVIRONMENT_DEV'     => '',
			'BACKEND_ENVIRONMENT_STAGE'   => '',
			'BACKEND_ENVIRONMENT_PREPROD' => '',
			'BACKEND_ENVIRONMENT_PROD'    => 'https://prod.backend.simply.in/api',
			'APP_VERSION_PREFIX_STAGE'    => 'st',
			'APP_VERSION_PREFIX_DEV'      => 'dev',
			'APP_VERSION_PREFIX_PREPROD'  => 'pp',
			'APP_VERSION_PREFIX_PROD'     => '',
			'APP_ENV'                     => 'prod',
		];
	}

	/**
	 * Resolve the backend API base URL for the current environment, without needing the
	 * plugin bootstrap (`simplyin()`, `$simplyin_config`) to have run — the same env-keyed
	 * selection as the bootstrap's own switch, exposed as a pure function so a standalone
	 * caller (uninstall.php, which WordPress loads without the plugin's main file) can use it.
	 *
	 * @param array<string, string>|null $env Env map to resolve against; defaults to {@see read()}.
	 *
	 * @return string Backend base URL, or '' if the selected environment has none configured.
	 */
	public static function resolve_backend_url( ?array $env = null ): string {
		$env     = $env ?? self::read();
		$app_env = (string) ( $env['APP_ENV'] ?? 'prod' );

		switch ( $app_env ) {
			case 'preprod':
				return (string) ( $env['BACKEND_ENVIRONMENT_PREPROD'] ?? '' );
			case 'stage':
				return (string) ( $env['BACKEND_ENVIRONMENT_STAGE'] ?? '' );
			case 'dev':
				return (string) ( $env['BACKEND_ENVIRONMENT_DEV'] ?? '' );
			default:
				return (string) ( $env['BACKEND_ENVIRONMENT_PROD'] ?? '' );
		}
	}
}
