<?php

namespace EasyLinkAutomations\Triggers\WordPress;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a specific post type is set to a specific status.
 */
final class PostTypeSetToStatusTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'wordpress/post_type_set_to_status';
    }

    public static function getName(): string
    {
        return __('Post of type set to status', 'easylink-automations');
    }

    public static function getDescription(): string
    {
        return __('Triggers when a specific post type is set to a specific status (including via REST API)', 'easylink-automations');
    }

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

    public static function getIcon(): string
    {
        return 'post';
    }

    public static function getOutputFields(): array
    {
        return [
            'post_id'        => ['label' => 'Post ID', 'type' => 'number'],
            'post_title'     => ['label' => 'Post Title', 'type' => 'string'],
            'post_content'   => ['label' => 'Post Content', 'type' => 'html'],
            'post_excerpt'   => ['label' => 'Post Excerpt', 'type' => 'string'],
            'post_url'       => ['label' => 'Post URL', 'type' => 'url'],
            'post_type'      => ['label' => 'Post Type', 'type' => 'string'],
            'post_status'    => ['label' => 'Post Status', 'type' => 'string'],
            'post_date'      => ['label' => 'Post Date', 'type' => 'datetime'],
            'post_author'    => ['label' => 'Author ID', 'type' => 'number'],
            'author_name'    => ['label' => 'Author Name', 'type' => 'string'],
            'author_email'   => ['label' => 'Author Email', 'type' => 'email'],
            'featured_image' => ['label' => 'Featured Image URL', 'type' => 'url'],
            'categories'     => ['label' => 'Categories', 'type' => 'array'],
            'tags'           => ['label' => 'Tags', 'type' => 'array'],
            'custom_metas'   => ['label' => 'Custom Meta Fields', 'type' => 'json'],
        ];
    }

    public static function getConfigFields(): array
    {
        return [
            'post_type' => [
                'label'    => 'Post Type',
                'type'     => 'select',
                'options'  => 'dynamic:post_types',
                'required' => true,
            ],
            'post_status' => [
                'label'    => 'Post Status',
                'type'     => 'select',
                'options'  => [
                    ['value' => 'publish', 'label' => 'Published'],
                    ['value' => 'draft',   'label' => 'Draft'],
                    ['value' => 'pending', 'label' => 'Pending'],
                    ['value' => 'private', 'label' => 'Private'],
                    ['value' => 'future',  'label' => 'Scheduled'],
                    ['value' => 'any',     'label' => 'Any'],
                ],
                'required' => true,
                'default'  => 'publish',
            ],
        ];
    }

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

        add_action('transition_post_status', function (string $newStatus, string $oldStatus, \WP_Post $post): void {
            if ($oldStatus === $newStatus) {
                return;
            }

            if (wp_is_post_revision($post->ID) || wp_is_post_autosave($post->ID)) {
                return;
            }

            $data = $this->handle($newStatus, $oldStatus, $post);
            $this->fire($data);
        }, 10, 3);
    }

    public function handle(mixed ...$args): array
    {
        $newStatus = $args[0];
        $post      = $args[2];
        $postId    = $post->ID;

        $author        = get_userdata($post->post_author);
        $featuredImage = wp_get_attachment_image_url(get_post_thumbnail_id($postId), 'full') ?: '';
        $categories    = wp_get_post_categories($postId, ['fields' => 'names']);
        $tags          = wp_get_post_tags($postId, ['fields' => 'names']);
        $customMetas   = get_post_meta($postId);

        return [
            'post_id'        => $postId,
            'post_title'     => $post->post_title,
            'post_content'   => $post->post_content,
            'post_excerpt'   => $post->post_excerpt,
            'post_url'       => get_permalink($postId),
            'post_type'      => $post->post_type,
            'post_status'    => $newStatus,
            'post_date'      => $post->post_date,
            'post_author'    => (int) $post->post_author,
            'author_name'    => $author->display_name ?? '',
            'author_email'   => $author->user_email ?? '',
            'featured_image' => $featuredImage,
            'categories'     => $categories,
            'tags'           => $tags,
            'custom_metas'   => $customMetas,
        ];
    }
}
