<?php
/**
 * Multisite network-level AI connection key fallbacks.
 *
 * @package WP_PowerSuite\AI
 */

namespace WP_PowerSuite\AI;

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

final class NetworkSettings {

	private const OPTION_PREFIX = 'wpps_network_ai_connections_';

	public static function isMultisite(): bool {
		return is_multisite();
	}

	public static function canManageNetworkKeys(): bool {
		return self::isMultisite() && current_user_can( 'manage_network_options' );
	}

	public static function resolve( string $site_value, string $field ): string {
		if ( $site_value !== '' ) {
			return $site_value;
		}

		if ( ! self::isMultisite() ) {
			return '';
		}

		$settings = ConnectionSettings::get();
		if ( empty( $settings['use_network_api_keys'] ) ) {
			return '';
		}

		$value = get_site_option( self::OPTION_PREFIX . sanitize_key( $field ), '' );

		return is_string( $value ) ? trim( $value ) : '';
	}

	public static function update( string $field, string $value ): bool {
		if ( ! self::canManageNetworkKeys() ) {
			return false;
		}

		return (bool) update_site_option( self::OPTION_PREFIX . sanitize_key( $field ), $value );
	}

	public static function getNetworkKey( string $field ): string {
		if ( ! self::isMultisite() ) {
			return '';
		}

		$value = get_site_option( self::OPTION_PREFIX . sanitize_key( $field ), '' );

		return is_string( $value ) ? trim( $value ) : '';
	}

	public static function isNetworkKeyConfigured( string $field ): bool {
		return self::getNetworkKey( $field ) !== '';
	}

	/** @return list<string> */
	public static function keyFields(): array {
		return ProviderRegistry::keyFields();
	}
}
