<?php

namespace EasyLinkAutomations\Triggers\WordPress;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a new user registers.
 */
final class UserRegisteredTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'wordpress/user_registered';
    }

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

    public static function getDescription(): string
    {
        return __('Triggers when a new user registers on the site', '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' => 'Email', 'type' => 'email'],
            'display_name' => ['label' => 'Display Name', 'type' => 'string'],
            'first_name'   => ['label' => 'First Name', 'type' => 'string'],
            'last_name'    => ['label' => 'Last Name', 'type' => 'string'],
            'user_url'     => ['label' => 'Website', 'type' => 'url'],
            'role'         => ['label' => 'Role', 'type' => 'string'],
            'registered'   => ['label' => 'Registration Date', 'type' => 'datetime'],
        ];
    }

    public static function getConfigFields(): array
    {
        return [
            'roles' => [
                'label'   => 'Only these roles (optional)',
                'type'    => 'multi_select',
                'options' => 'dynamic:roles',
            ],
        ];
    }

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

        add_action('user_register', function ($userId): void {
            $user = get_userdata($userId);

            if (!$user) {
                return;
            }

            $data = $this->handle($user);
            $this->fire($data);
        }, 10, 1);
    }

    public function handle(mixed ...$args): array
    {
        $user = $args[0];

        return [
            'user_id'      => $user->ID,
            '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,
            'user_url'     => $user->user_url,
            'role'         => $user->roles[0] ?? '',
            'registered'   => $user->user_registered,
        ];
    }
}
