<?php

namespace EasyLinkAutomations\Triggers\WordPress;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a user's primary role is replaced with a new role.
 */
final class UserRoleUpdatedTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'wordpress/user_role_updated';
    }

    public static function getName(): string
    {
        return __('User role updated', 'easylink-automations');
    }

    public static function getDescription(): string
    {
        return __('Triggers when a user\'s primary role is replaced with a new role', 'easylink-automations');
    }

    public static function getCategory(): string
    {
        return 'WordPress';
    }

    public static function getIcon(): string
    {
        return 'user-add';
    }

    public static function getOutputFields(): array
    {
        return [
            'user_id'      => ['label' => 'User ID', 'type' => 'number'],
            'user_login'   => ['label' => 'Username', 'type' => 'string'],
            'user_email'   => ['label' => 'User Email', 'type' => 'email'],
            'display_name' => ['label' => 'Display Name', 'type' => 'string'],
            'first_name'   => ['label' => 'First Name', 'type' => 'string'],
            'last_name'    => ['label' => 'Last Name', 'type' => 'string'],
            'new_role'     => ['label' => 'New Role', 'type' => 'string'],
        ];
    }

    public static function getConfigFields(): array
    {
        return [
            'role' => [
                'label'    => 'Only this role (optional)',
                'type'     => 'select',
                'options'  => 'dynamic:roles',
                'required' => false,
            ],
        ];
    }

    public function register(callable $callback): void
    {
        $this->callback = $callback;

        add_action('set_user_role', function (int $userId, string $newRole, array $oldRoles): void {
            $data = $this->handle($userId, $newRole);
            $this->fire($data);
        }, 10, 3);
    }

    public function handle(mixed ...$args): array
    {
        $userId  = (int) $args[0];
        $newRole = (string) $args[1];

        $user = get_userdata($userId);

        return [
            'user_id'      => $userId,
            'user_login'   => $user->user_login ?? '',
            'user_email'   => $user->user_email ?? '',
            'display_name' => $user->display_name ?? '',
            'first_name'   => $user->first_name ?? '',
            'last_name'    => $user->last_name ?? '',
            'new_role'     => $newRole,
        ];
    }
}
