<?php

namespace EasyLinkAutomations\Actions\Freshservice;

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

use EasyLinkAutomations\Actions\BaseAction;

final class CreateTicketAction extends BaseAction
{
    public static function getSlug(): string { return 'freshservice/create_ticket'; }
    public static function getName(): string { return __('Create Ticket', 'easylink-automations'); }
    public static function getDescription(): string { return __('Create a support ticket in Freshservice', 'easylink-automations'); }
    public static function getCategory(): string { return 'Freshservice'; }
    public static function getIcon(): string { return 'freshservice'; }
    public static function getRequiresConnection(): ?string { return 'freshservice'; }

    public static function getConfigFields(): array
    {
        return [
            'email' => self::text('Requester Email', false),
            'requester_id' => self::remote('Requester', 'freshservice/requesters', 'requesters', false),
            'subject' => self::text('Subject', true),
            'description' => [
                'label' => 'Description', 'type' => 'textarea', 'required' => true, 'supports_mapping' => true,
            ],
            'priority' => self::select('Priority', [1 => 'Low', 2 => 'Medium', 3 => 'High', 4 => 'Urgent'], 1),
            'status' => self::select('Status', [2 => 'Open', 3 => 'Pending', 4 => 'Resolved', 5 => 'Closed'], 2),
            'department_id' => self::remote('Department', 'freshservice/departments', 'departments', false),
            'group_id' => self::remote('Agent Group', 'freshservice/agent-groups', 'agent_groups', false),
            'workspace_id' => self::text('Workspace ID', false, 'Optional for accounts with multiple workspaces.'),
            'cc_emails' => self::text('CC Emails', false, 'Comma-separated email addresses.'),
        ];
    }

    public function execute(array $triggerData, array $config): array
    {
        $mapped = $this->mapConfig($config, $triggerData);
        $missing = $this->validateRequired($mapped);
        if ($missing) {
            return ['success' => false, 'message' => 'Missing required fields after mapping: ' . implode(', ', $missing), 'data' => []];
        }
        if (empty($mapped['email']) && empty($mapped['requester_id'])) {
            return ['success' => false, 'message' => 'Requester Email or Requester is required', 'data' => []];
        }

        $body = [
            'subject' => trim((string) $mapped['subject']),
            'description' => (string) $mapped['description'],
            'priority' => (int) ($mapped['priority'] ?? 1),
            'status' => (int) ($mapped['status'] ?? 2),
        ];
        foreach (['email', 'requester_id', 'department_id', 'group_id', 'workspace_id'] as $key) {
            if (!empty($mapped[$key])) {
                $body[$key] = str_ends_with($key, '_id') ? (int) $mapped[$key] : trim((string) $mapped[$key]);
            }
        }
        if (!empty($mapped['cc_emails'])) {
            $body['cc_emails'] = array_values(array_filter(array_map('trim', explode(',', (string) $mapped['cc_emails']))));
        }

        return FreshserviceRequestHelper::request((int) ($config['connection_id'] ?? 0), 'POST', 'tickets', $body);
    }

    private static function text(string $label, bool $required, string $description = ''): array
    {
        return array_filter([
            'label' => $label, 'type' => 'text', 'required' => $required,
            'supports_mapping' => true, 'description' => $description,
        ]);
    }

    private static function remote(string $label, string $source, string $key, bool $required): array
    {
        return [
            'label' => $label, 'type' => 'remote_select', 'required' => $required,
            'supports_mapping' => true, 'remote_source' => $source, 'options_key' => $key,
        ];
    }

    private static function select(string $label, array $options, int $default): array
    {
        $items = [];
        foreach ($options as $value => $name) {
            $items[] = ['value' => (string) $value, 'label' => $name];
        }
        return ['label' => $label, 'type' => 'select', 'required' => true, 'default' => $default, 'options' => $items];
    }
}
