<?php
/**
 * Role-to-scheme resolution with deterministic priority.
 *
 * @package WP_PowerSuite\AdminColorCustomizer
 */

namespace WP_PowerSuite\AdminColorCustomizer;

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

class Role_Resolver {

	/**
	 * @return list<string>
	 */
	public static function get_role_priority(): array {
		$default = [
			'administrator',
			'editor',
			'author',
			'contributor',
			'subscriber',
		];

		$editable = array_keys( get_editable_roles() );
		$custom   = array_values(
			array_diff(
				array_map( 'strval', $editable ),
				$default
			)
		);
		sort( $custom, SORT_STRING );

		$priority = array_merge( $default, $custom );

		/** @var list<string> $filtered */
		$filtered = apply_filters( 'wpps_admin_color_customizer_role_priority', $priority );

		$filtered = array_values(
			array_filter(
				array_map( 'sanitize_key', $filtered ),
				static fn( string $role ): bool => $role !== '' && in_array( $role, $editable, true )
			)
		);

		return $filtered !== [] ? $filtered : $priority;
	}

	/**
	 * @param array<string, mixed> $settings
	 */
	public static function resolve_scheme_id_for_user( int $user_id, array $settings ): ?string {
		$user = get_userdata( $user_id );
		if ( ! $user instanceof \WP_User ) {
			return null;
		}

		$role_schemes = is_array( $settings['role_schemes'] ?? null ) ? $settings['role_schemes'] : [];
		if ( $role_schemes === [] ) {
			return null;
		}

		$registry = Scheme_Registry::instance();
		$valid    = $registry->get_all_scheme_ids( $settings );
		$user_roles = (array) $user->roles;

		foreach ( self::get_role_priority() as $role ) {
			if ( ! in_array( $role, $user_roles, true ) ) {
				continue;
			}
			if ( ! isset( $role_schemes[ $role ] ) ) {
				continue;
			}
			$scheme_id = sanitize_key( (string) $role_schemes[ $role ] );
			if ( in_array( $scheme_id, $valid, true ) ) {
				return $scheme_id;
			}
		}

		return null;
	}
}
