<?php

namespace Lean\Console\Form\Storage\Database;

use Picea\Ui\Method\{ FormInterface, FormContext, FormContextInterface };

use \Lean\Console\{ Lib, Entity };

use Picea\Compiler\Context;
use Psr\Http\Message\ServerRequestInterface;
use Ulmus\{ EntityCollection };

class Import implements FormInterface
{
    protected ? Lib\DatabaseMigrations $migration;

    protected array $connections;

    public function __construct(Lib\DatabaseMigrations $migration, array $connections)
    {
        $this->migration = $migration;
        $this->connections = $connections;
    }

    public function initialize(FormContextInterface $context) : void
    {
        $context->sourceTables ??= new EntityCollection();
        $context->destinationTables ??= new EntityCollection();

    }

    public function validate(FormContextInterface $context) : bool
    {
        if ($context->source) {
            $filtered = array_filter($this->migration->entities, fn($e, $key) => $key::repository()->adapter->name === $context->source, ARRAY_FILTER_USE_BOTH);
            $context->sourceTables->replaceWith($filtered);
        }

        return $context->valid();
    }

    public function execute(FormContextInterface $context) : void
    {
        if ($context->copy) {
            foreach (array_filter($context->copy) as $dest => $source) {
                foreach($source::repository()->yield() as $src) {
                    $dest::repository()->save( $src->toArray(), null, true );
                }
            }
        }
    }

    public static function getContext(ServerRequestInterface $request, ? string $formName = null) : FormContextInterface
    {
        return new class($request, $formName) extends FormContext {

            public EntityCollection $sourceTables;

            public EntityCollection $destinationTables;

        };
    }
}