<?php

declare(strict_types=1);

namespace App\Framework\Admin\Factories;

use App\Framework\Admin\FormFields\FormFieldFactory;
use App\Framework\Admin\ValueObjects\AdminFormConfig;
use App\Framework\Http\Session\FormIdGenerator;
use App\Framework\View\FormBuilder;

/**
 * Admin Form Factory
 *
 * Creates admin forms using composition-based field system
 */
final readonly class AdminFormFactory
{
    public function __construct(
        private FormIdGenerator $formIdGenerator,
        private FormFieldFactory $fieldFactory
    ) {
    }

    public function create(AdminFormConfig $config): FormBuilder
    {
        // Use existing FormBuilder
        $form = FormBuilder::create(
            action: $config->action,
            method: $config->method->value,
            formIdGenerator: $this->formIdGenerator
        )->withClass('admin-form');

        // Create fields using composition-based field factory
        foreach ($config->fields as $name => $fieldConfig) {
            // Merge field config with data value
            $fieldConfigWithValue = [
                ...$fieldConfig,
                'name' => $name,
                'value' => $config->data[$name] ?? null,
            ];

            // Create field using factory
            $field = $this->fieldFactory->createFromConfig($fieldConfigWithValue);

            // Render field to form
            $form = $field->render($form);
        }

        return $form->addSubmitButton('Save');
    }
}
