<?php

namespace EasyLinkAutomations\Actions\WordPress;

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

use EasyLinkAutomations\Actions\BaseAction;

/**
 * Action that creates a new WordPress post.
 */
final class CreatePostAction extends BaseAction
{
    public static function getSlug(): string
    {
        return 'wordpress/create_post';
    }

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

    public static function getDescription(): string
    {
        return __('Create a new WordPress post or custom post type', 'easylink-automations');
    }

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

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

    public static function getConfigFields(): array
    {
        return [
            'post_type' => [
                'label'         => 'Post Type',
                'type'          => 'remote_select',
                'remote_source' => 'wordpress/post-types',
                'options_key'   => 'post_types',
                'default'       => 'post',
            ],
            'field_mappings' => [
                'label'            => 'Post Fields',
                'type'             => 'field_mapping',
                'required'         => true,
                'remote_source'    => 'wordpress/post-fields',
                'depends_on'       => ['post_type'],
                'options_key'      => 'columns',
                'supports_mapping' => true,
            ],
        ];
    }

    public function execute(array $triggerData, array $config): array
    {
        $fieldMappings = $this->mapValue($config['field_mappings'] ?? [], $triggerData);

        // Ensure required fields
        if (empty($fieldMappings['post_title'])) {
            return [
                'success' => false,
                'message' => 'Post title is required',
            ];
        }

        $postData = [
            'post_type'   => $config['post_type'] ?? 'post',
            'post_title'  => $fieldMappings['post_title'],
        ];

        // Map standard post fields
        $standardFields = ['post_content', 'post_excerpt', 'post_status', 'post_author', 'post_date', 'post_name', 'post_password', 'post_parent', 'menu_order', 'comment_status', 'ping_status'];
        foreach ($standardFields as $field) {
            if (!empty($fieldMappings[$field])) {
                $postData[$field] = $fieldMappings[$field];
            }
        }

        // Default status if not set
        if (empty($postData['post_status'])) {
            $postData['post_status'] = 'draft';
        }

        $postId = wp_insert_post($postData, true);

        if (is_wp_error($postId)) {
            return [
                'success' => false,
                'message' => 'Failed to create post: ' . $postId->get_error_message(),
            ];
        }

        // Handle taxonomy fields (tax_category, tax_post_tag, etc.)
        foreach ($fieldMappings as $key => $value) {
            if (str_starts_with($key, 'tax_') && !empty($value)) {
                $taxonomy = substr($key, 4);
                $rawTerms = is_array($value) ? $value : explode(',', (string) $value);
                $terms    = array_values(array_filter(array_map(
                    static function ($term) {
                        $term = trim((string) $term);

                        return ctype_digit($term) ? (int) $term : $term;
                    },
                    $rawTerms
                ), static fn($term) => $term !== ''));

                if (empty($terms)) {
                    continue;
                }

                $termResult = wp_set_object_terms($postId, $terms, $taxonomy);
                if (is_wp_error($termResult)) {
                    return [
                        'success' => false,
                        'message' => sprintf(
                            'Post created, but failed to set %s terms: %s',
                            $taxonomy,
                            $termResult->get_error_message()
                        ),
                        'data'    => [
                            'post_id'  => $postId,
                            'post_url' => get_permalink($postId),
                        ],
                    ];
                }
            }
        }

        return [
            'success' => true,
            'message' => 'Post created successfully',
            'data'    => [
                'post_id'  => $postId,
                'post_url' => get_permalink($postId),
            ],
        ];
    }
}
