<?php

namespace GriffinForms\Includes\Migration;

use GriffinForms\Traits\Singleton;

class MigrationRegistry
{
    use Singleton;

    /** @var array<string, MigrationSourceInterface> */
    private array $sources = [];

    protected function setData()
    {
        $this->registerBundledSources();
    }

    public function register(MigrationSourceInterface $source): void
    {
        $this->sources[$source->getSlug()] = $source;
    }

    /**
     * @return MigrationSourceInterface[]
     */
    public function getSources(): array
    {
        return array_values($this->sources);
    }

    /**
     * @return MigrationSourceInterface[]
     */
    public function getInstalledSources(): array
    {
        return array_values(array_filter(
            $this->sources,
            static fn(MigrationSourceInterface $source): bool => $source->isInstalled()
        ));
    }

    public function getSource(string $slug): ?MigrationSourceInterface
    {
        $slug = sanitize_key($slug);
        return $this->sources[$slug] ?? null;
    }

    private function registerBundledSources(): void
    {
        $classes = [
            \GriffinForms\Includes\Migration\Sources\ContactForm7Source::class,
            \GriffinForms\Includes\Migration\Sources\WpFormsSource::class,
            \GriffinForms\Includes\Migration\Sources\NinjaFormsSource::class,
            \GriffinForms\Includes\Migration\Sources\FormidableFormsSource::class,
        ];

        foreach ($classes as $class) {
            if (!class_exists($class)) {
                continue;
            }

            $source = new $class();
            if ($source instanceof MigrationSourceInterface) {
                $this->register($source);
            }
        }
    }
}
