<?php

declare(strict_types=1);

namespace App\Framework\OpenApi;

/**
 * Service for programmatic access to OpenAPI specification
 */
final readonly class OpenApiService
{
    public function __construct(
        private OpenApiGenerator $generator,
    ) {
    }

    public function getSpecification(): OpenApiSpec
    {
        $info = new OpenApiInfo(
            title: 'API',
            version: '1.0.0',
        );

        return $this->generator->generate($info);
    }

    public function getEndpoints(): array
    {
        $spec = $this->getSpecification();
        $endpoints = [];

        foreach ($spec->paths as $path => $pathItem) {
            foreach ($pathItem as $method => $operation) {
                $endpoints[] = [
                    'method' => strtoupper($method),
                    'path' => $path,
                    'summary' => $operation['summary'] ?? '',
                    'tags' => $operation['tags'] ?? [],
                ];
            }
        }

        return $endpoints;
    }

    public function getEndpointsByTag(string $tag): array
    {
        return array_filter(
            $this->getEndpoints(),
            fn ($endpoint) => in_array($tag, $endpoint['tags'])
        );
    }
}
