<?php

namespace EasyLinkAutomations\Triggers\WordPress;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a user resets their password.
 */
final class UserPasswordResetTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'wordpress/user_password_reset';
    }

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

    public static function getDescription(): string
    {
        return __('Triggers when a user resets their password (works with WooCommerce too)', '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'],
            'role'         => ['label' => 'Role', 'type' => 'string'],
        ];
    }

    public static function getConfigFields(): array
    {
        return [];
    }

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

        add_action('after_password_reset', function (\WP_User $user): void {
            if (!isset($user->ID)) {
                return;
            }

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

        add_action('woocommerce_customer_reset_password', function (\WP_User $user): void {
            if (!isset($user->ID)) {
                return;
            }

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

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

        return [
            'user_id'      => (int) $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 ?? '',
            'role'         => $roles[0] ?? '',
        ];
    }
}
