<?php

namespace Waypoint\Agent\Auth;

use Waypoint\Agent\Base\Thing;

class Role_Manager extends Thing {

	const ROLE       = 'waypoint_super_admin';
	const CAP        = 'set_waypoint_helper_settings';
	const ROLE_LABEL = 'Waypoint Super Admin';

	public function attach_hooks(): void {
		add_action( 'user_register', [ $this, 'maybe_assign_first_super_admin' ] );
	}

	public static function register_role(): void {
		if ( ! get_role( self::ROLE ) ) {
			add_role( self::ROLE, self::ROLE_LABEL, [ self::CAP => true ] );
		}
	}

	public static function assign( int $user_id ): bool {
		$user = get_user_by( 'id', $user_id );
		if ( ! $user ) {
			return false;
		}
		$user->add_role( self::ROLE );
		return true;
	}

	public static function has_any_super_admin(): bool {
		$users = get_users( [
			'role'   => self::ROLE,
			'number' => 1,
			'fields' => 'ids',
		] );
		return ! empty( $users );
	}

	public function maybe_assign_first_super_admin( int $user_id ): void {
		if ( self::has_any_super_admin() ) {
			return;
		}
		self::assign( $user_id );
	}
}
