<?php

namespace EasyLinkAutomations\HTTP\Controllers;

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

use EasyLinkAutomations\Config;
use EasyLinkAutomations\Data\ProCatalog;
use EasyLinkAutomations\HTTP\Request\Request;
use EasyLinkAutomations\HTTP\Response;
use EasyLinkAutomations\Triggers\TriggerRegistry;

/**
 * REST API controller for triggers.
 */
final class TriggerController
{
    /**
     * Get all available triggers.
     */
    public function index(Request $request): Response
    {
        $grouped = $request->get('grouped') === 'true';

        if ($grouped) {
            $data = TriggerRegistry::groupedByCategory();

            if (!Config::isProActivated()) {
                foreach (ProCatalog::triggers() as $item) {
                    $data[$item['category']][] = $item;
                }
                ksort($data);
            }
        } else {
            $data = TriggerRegistry::toArray();

            if (!Config::isProActivated()) {
                $data = array_merge($data, ProCatalog::triggers());
            }
        }

        return Response::success($data);
    }

    /**
     * Get a specific trigger's details.
     */
    public function show(Request $request, string $slug): Response
    {
        $trigger = TriggerRegistry::get($slug);

        if (!$trigger) {
            return Response::error('Trigger not found', 404);
        }

        return Response::success($trigger::toArray());
    }

    /**
     * Return discovered sample fields for a trigger.
     *
     * When an automation with this trigger has run at least once, returns the
     * flattened field keys+values from the most recent execution so the UI can
     * populate the dynamic-field selector beyond the static outputFields.
     * Falls back to the static outputFields when no sample is available.
     */
    public function sampleFields(Request $request): Response
    {
        $slug = trim((string) $request->get('trigger_slug', ''));
        if ($slug === '') {
            return Response::error('Missing trigger_slug', 400);
        }

        $transientKey = 'easylink_automations_trigger_sample_' . sanitize_key($slug);
        $stored       = get_transient($transientKey);

        if ($stored) {
            $fields = json_decode($stored, true);
            if (is_array($fields)) {
                return Response::success(['fields' => $fields, 'source' => 'sample']);
            }
        }

        // Fall back: expose the static output fields as key => label pairs
        $trigger = TriggerRegistry::get($slug);
        if ($trigger) {
            $fields = [];
            foreach ($trigger::getOutputFields() as $key => $definition) {
                $fields[$key] = $definition['label'] ?? $key;
            }
            return Response::success(['fields' => $fields, 'source' => 'static']);
        }

        return Response::success(['fields' => [], 'source' => 'none']);
    }
}
