<?php

declare(strict_types=1);

namespace App\Framework\FormGenerator;

use App\Framework\LiveComponents\FormBuilder\FieldType;
use App\Framework\Validation\Rules\Email;
use App\Framework\Validation\Rules\Phone;
use App\Framework\Validation\Rules\Url;
use ReflectionProperty;

/**
 * Resolves Form Field Type from PHP Type + Validation Attributes
 */
final readonly class FieldTypeResolver
{
    /**
     * Resolve field type
     *
     * Priority:
     * 1. Validation Attributes (#[Email] → EMAIL)
     * 2. PHP Type (bool → CHECKBOX, int → NUMBER)
     * 3. Default (TEXT)
     *
     * @param array<object> $validationAttributes
     */
    public function resolve(ReflectionProperty $property, array $validationAttributes): FieldType
    {
        // Priority 1: Check validation attributes
        foreach ($validationAttributes as $attr) {
            $fieldType = $this->resolveFromValidationAttribute($attr);
            if ($fieldType !== null) {
                return $fieldType;
            }
        }

        // Priority 2: Check PHP type
        $type = $property->getType();
        if ($type) {
            $typeName = $type->getName();
            $fieldType = $this->resolveFromPhpType($typeName);
            if ($fieldType !== null) {
                return $fieldType;
            }
        }

        // Priority 3: Default
        return FieldType::TEXT;
    }

    /**
     * Resolve from validation attribute
     */
    private function resolveFromValidationAttribute(object $attribute): ?FieldType
    {
        return match (true) {
            $attribute instanceof Email => FieldType::EMAIL,
            $attribute instanceof Phone => FieldType::TEXT, // Could be TEL if we add it
            $attribute instanceof Url => FieldType::TEXT, // Could be URL if we add it
            default => null
        };
    }

    /**
     * Resolve from PHP type
     */
    private function resolveFromPhpType(string $typeName): ?FieldType
    {
        return match ($typeName) {
            'bool' => FieldType::CHECKBOX,
            'int', 'float' => FieldType::TEXT, // Could add NUMBER type
            'string' => FieldType::TEXT,
            default => null
        };
    }
}
