<?php

namespace Limb_Chatbot\Includes\Services\Notifications;

use Limb_Chatbot\Includes\Data_Objects\Chatbot_User;

/**
 * Resolves Chatbot_User to a notification role slug for type filtering.
 *
 * Maps user type and WP capabilities to: guest, user, agent, admin.
 *
 * @package Limb_Chatbot\Includes\Services\Notifications
 * @since 1.0.15
 */
class Notification_Role_Resolver {

	/**
	 * Role: guest (unauthenticated visitor).
	 */
	const ROLE_GUEST = 'guest';

	/**
	 * Role: registered WordPress user (no admin).
	 */
	const ROLE_USER = 'user';

	/**
	 * Role: live agent.
	 */
	const ROLE_AGENT = 'agent';

	/**
	 * Role: WordPress admin (manage_options).
	 */
	const ROLE_ADMIN = 'admin';

	/**
	 * Resolve the notification role for a chatbot user.
	 *
	 * @param  Chatbot_User  $chatbot_user  Chatbot user.
	 *
	 * @return string One of ROLE_GUEST, ROLE_USER, ROLE_AGENT, ROLE_ADMIN.
	 * @since 1.0.15
	 */
	public function resolve( Chatbot_User $chatbot_user ): string {
		if ( $chatbot_user->get_type() === Chatbot_User::TYPE_AGENT ) {
			return self::ROLE_AGENT;
		}

		if ( $chatbot_user->get_type() === Chatbot_User::TYPE_GUEST ) {
			return self::ROLE_GUEST;
		}

		if ( $chatbot_user->get_type() === Chatbot_User::TYPE_WP_USER && $chatbot_user->get_wp_user_id() ) {
			// Use the WP user's capabilities directly, not the "current user" context.
			// Notifications may run in Action Scheduler (no logged-in admin).
			$wp_user = get_userdata( (int) $chatbot_user->get_wp_user_id() );
			if ( $wp_user && user_can( $wp_user, 'manage_options' ) ) {
				return self::ROLE_ADMIN;
			}
		}

		return self::ROLE_USER;
	}
}
