<?php

declare(strict_types=1);

namespace App\Framework\GraphQL\Schema;

use App\Framework\GraphQL\ValueObjects\GraphQLTypeName;

/**
 * Represents a GraphQL type definition
 *
 * Can be Object Type, Input Type, or Interface
 */
final readonly class TypeDefinition
{
    /**
     * @param array<string, FieldDefinition> $fields
     */
    public function __construct(
        public GraphQLTypeName $name,
        public array $fields,
        public ?string $description = null,
        public bool $isInput = false,
        public bool $isInterface = false
    ) {
    }

    /**
     * Convert to GraphQL schema definition language (SDL)
     */
    public function toSDL(): string
    {
        $lines = [];

        // Add description as comment
        if ($this->description !== null) {
            $lines[] = '"""';
            $lines[] = $this->description;
            $lines[] = '"""';
        }

        // Type keyword
        $keyword = match (true) {
            $this->isInput => 'input',
            $this->isInterface => 'interface',
            default => 'type'
        };

        $lines[] = "{$keyword} {$this->name->toString()} {";

        // Add fields
        foreach ($this->fields as $field) {
            $fieldSDL = '  ' . $field->toSDL();
            $lines[] = $fieldSDL;
        }

        $lines[] = '}';

        return implode("\n", $lines);
    }

    /**
     * Get field by name
     */
    public function getField(string $name): ?FieldDefinition
    {
        return $this->fields[$name] ?? null;
    }
}
