<?php

namespace EasyLinkAutomations\Actions\Trello;

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

use EasyLinkAutomations\Actions\BaseAction;
use EasyLinkAutomations\Models\Connection;

/**
 * Creates a new Trello card in a list.
 */
final class CreateCardAction extends BaseAction
{
    public static function getSlug(): string
    {
        return 'trello/create_card';
    }

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

    public static function getDescription(): string
    {
        return __('Creates a new card in a Trello list.', 'easylink-automations');
    }

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

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


    public static function getRequiresConnection(): ?string
    {
        return 'trello';
    }

    public static function getConfigFields(): array
    {
        return [
            'board_id' => [
                'label'            => 'Board',
                'type'             => 'remote_select',
                'required'         => true,
                'remote_source'    => 'trello/boards',
                'depends_on'       => ['connection_id'],
                'options_key'      => 'boards',
                'supports_mapping' => true,
                'note'             => 'Select the board containing the target list.',
            ],
            'list_id' => [
                'label'            => 'List',
                'type'             => 'remote_select',
                'required'         => true,
                'remote_source'    => 'trello/lists',
                'depends_on'       => ['connection_id', 'board_id'],
                'options_key'      => 'lists',
                'supports_mapping' => true,
            ],
            'name' => [
                'label'            => 'Card Name',
                'type'             => 'text',
                'required'         => true,
                'placeholder'      => 'My new card',
                'supports_mapping' => true,
            ],
            'description' => [
                'label'            => 'Description',
                'type'             => 'textarea',
                'required'         => false,
                'placeholder'      => 'Card description...',
                'supports_mapping' => true,
            ],
            'due' => [
                'label'            => 'Due Date',
                'type'             => 'text',
                'required'         => false,
                'placeholder'      => '2024-12-31T23:59:59.000Z',
                'supports_mapping' => true,
                'note'             => 'ISO 8601 date string for the card due date.',
            ],
            'position' => [
                'label'   => 'Position',
                'type'    => 'select',
                'required' => false,
                'options' => [
                    ['value' => 'bottom', 'label' => 'Bottom'],
                    ['value' => 'top', 'label' => 'Top'],
                ],
            ],
        ];
    }

    public function execute(array $triggerData, array $config): array
    {
        $missing = $this->validateRequired($config);
        if ($missing) {
            return ['success' => false, 'message' => 'Missing: ' . implode(', ', $missing)];
        }

        $connectionId = (int) ($config['connection_id'] ?? 0);
        $connection   = Connection::find($connectionId);
        if (!$connection) {
            return ['success' => false, 'message' => 'Invalid connection'];
        }

        $credentials = Connection::getCredentials($connection);
        $apiKey      = $credentials['api_key'] ?? '';
        $apiToken    = $credentials['api_token'] ?? '';

        if (empty($apiKey) || empty($apiToken)) {
            return ['success' => false, 'message' => 'Incomplete connection credentials'];
        }

        $mapped = $this->mapConfig($config, $triggerData);
        $listId = trim($mapped['list_id'] ?? '');
        $name   = trim($mapped['name'] ?? '');

        if (empty($listId) || empty($name)) {
            return ['success' => false, 'message' => 'List and card name are required'];
        }

        $params = [
            'idList' => $listId,
            'name'   => $name,
            'key'    => $apiKey,
            'token'  => $apiToken,
        ];

        if (!empty($mapped['description'])) {
            $params['desc'] = $mapped['description'];
        }
        if (!empty($mapped['due'])) {
            $params['due'] = $mapped['due'];
        }
        if (!empty($mapped['position'])) {
            $params['pos'] = $mapped['position'];
        }

        $url      = 'https://api.trello.com/1/cards?' . http_build_query($params);
        $response = wp_remote_post($url, ['timeout' => 30]);

        if (is_wp_error($response)) {
            return ['success' => false, 'message' => $response->get_error_message()];
        }

        $code = wp_remote_retrieve_response_code($response);
        $data = json_decode(wp_remote_retrieve_body($response), true);

        $success = $code >= 200 && $code < 300;

        return [
            'success' => $success,
            'message' => $success ? 'Card created successfully' : 'Failed (HTTP ' . $code . '): ' . ($data['message'] ?? 'Unknown error'),
            'data'    => $data ?? [],
        ];
    }
}
