<?php

namespace EasyLinkAutomations\HTTP\Controllers;

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

use EasyLinkAutomations\Actions\ActionRegistry;
use EasyLinkAutomations\Config;
use EasyLinkAutomations\Data\ProCatalog;
use EasyLinkAutomations\HTTP\Request\Request;
use EasyLinkAutomations\HTTP\Response;

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

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

            if (!Config::isProActivated()) {
                foreach (ProCatalog::actions() as $item) {
                    $key = $item['category'] ?: '_uncategorized';
                    $data[$key][] = $item;
                }
                ksort($data);
            }
        } else {
            $data = ActionRegistry::toArray();

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

        return Response::success($data);
    }

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

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

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