<?php

declare(strict_types=1);

namespace KupShop\GraphQLBundle\Contracts;

use KupShop\KupShopBundle\Util\ObjectUtil;
use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag;
use TheCodingMachine\GraphQLite\Annotations\Field;

#[AutoconfigureTag(name: self::SERVICE_TAG)]
abstract class AbstractDataType
{
    public const SERVICE_TAG = 'kupshop.graphql.type.data';

    #[Field]
    public ?int $_;

    private ?array $properties = null;

    public function __construct(?array $data = null)
    {
        $this->initializeData($data);
    }

    public function asArray(): array
    {
        $data = [];

        foreach ($this->getProperties() as $name => $_) {
            if (!ObjectUtil::isPropertyInitialized($this, $name)) {
                continue;
            }

            $data[$name] = $this->{$name} ?? null;
        }

        return $data;
    }

    protected function initializeData(?array $data = null): void
    {
        foreach ($this->getProperties() as $name => $property) {
            $this->{$name} = $this->resolvePropertyValue($data[$name] ?? null, $property);
        }
    }

    /**
     * @return array<string, \ReflectionProperty>
     */
    private function getProperties(): array
    {
        if ($this->properties === null) {
            $this->properties = [];

            $refClass = new \ReflectionClass($this);
            foreach ($refClass->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
                $this->properties[$property->getName()] = $property;
            }
        }

        return $this->properties;
    }

    private function resolvePropertyValue(mixed $value, \ReflectionProperty $property): mixed
    {
        if (empty($value)) {
            return null;
        }

        $type = $property->getType();

        // TODO: do budoucna muzeme zacit umet handlovat zanoreni do dalsich GraphQL typu, datetime atd...
        // TODO: ale bude potřeba to dělat i zpětně, aby GraphQL typ se uměl zkonverit na custom data
        if (!($type instanceof \ReflectionNamedType) || !$type->isBuiltin()) {
            return null;
        }

        // handle built-in types
        return match ($type->getName()) {
            'int' => (int) $value,
            'float' => (float) $value,
            'bool' => (bool) $value,
            'string' => (string) $value,
            default => null,
        };
    }
}
