<?php

declare(strict_types=1);

/**
 * APO-269 — GET /api/v1/content/search?q=...
 *
 * Public site-search query endpoint. Wraps MyronSearchIndexService::query()
 * and exposes the same primitive to MCP clients as `content_search` so AI
 * agents reach the same index the public /search page renders.
 */
final class MyronSearchContentAction implements MyronAction
{
    public function __construct(private readonly MyronSearchIndexService $service)
    {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/content/search',
            method: 'GET',
            domain: 'content',
            resource: 'search',
            verb: 'query',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'q' => ['type' => 'string'],
                    'limit' => ['type' => 'integer'],
                    'entityType' => ['type' => 'string'],
                    'bundleId' => ['type' => 'string'],
                ],
                'required' => ['q'],
            ],
            outputSchema: [
                'type' => 'object',
                'properties' => [
                    'results' => ['type' => 'array'],
                    'total' => ['type' => 'integer'],
                    'q' => ['type' => 'string'],
                ],
            ],
            requiredScope: MyronApiScopes::CONTENT_READ,
            summary: 'Full-text search over published content (V1: pages only). Returns title, path, url, snippet per hit.',
            audienceClass: 3,
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        $entitlement = $this->requireCapability('search.public');
        if ($entitlement !== null) {
            return $entitlement;
        }
        $q = trim((string) ($input['q'] ?? ''));
        if ($q === '') {
            return MyronActionResult::error('input_invalid', 'q is required.');
        }
        $opts = [];
        if (isset($input['limit'])) {
            $limit = (int) $input['limit'];
            if ($limit < 1) {
                return MyronActionResult::error('input_invalid', 'limit must be >= 1.');
            }
            $opts['limit'] = $limit;
        }
        if (isset($input['entityType']) && trim((string) $input['entityType']) !== '') {
            $opts['entityType'] = trim((string) $input['entityType']);
        }
        if (isset($input['bundleId']) && trim((string) $input['bundleId']) !== '') {
            $opts['bundleId'] = trim((string) $input['bundleId']);
        }
        try {
            $payload = $this->service->query($q, $opts);
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', 'Search service failed: ' . $e->getMessage());
        }
        return MyronActionResult::ok($payload);
    }

    private function requireCapability(string $capability): ?MyronActionResult
    {
        if (!function_exists('myronEntitlementGate')) {
            return null;
        }
        try {
            $decision = myronEntitlementGate()->evaluate($capability);
        } catch (Throwable) {
            return MyronActionResult::error('entitlement_denied', 'This feature is not available for the current license.');
        }
        return in_array((string) ($decision['outcome'] ?? ''), ['allowed', 'warn'], true)
            ? null
            : MyronActionResult::error('entitlement_denied', 'This feature is not available for the current license.');
    }
}
