<?php

namespace App\Extensions\Installed\Importer\Services\ApiAdapters;

use Illuminate\Support\Collection;

class ApiAdapterRegistry
{
    protected static array $adapters = [
        'freshdesk' => FreshdeskAdapter::class,
        'zendesk' => ZendeskAdapter::class,
        'helpscout' => HelpScoutAdapter::class,
    ];

    public static function register(string $class): void
    {
        if (!is_subclass_of($class, ApiImportAdapter::class)) {
            throw new \InvalidArgumentException("{$class} must implement ApiImportAdapter.");
        }
        static::$adapters[$class::id()] = $class;
    }

    public static function all(): array
    {
        $map = [];
        foreach (static::$adapters as $key => $class) {
            $map[is_string($key) ? $key : $class::id()] = $class;
        }
        return $map;
    }

    public static function adapterClass(string $id): ?string
    {
        return static::all()[$id] ?? null;
    }

    public static function resolve(string $id): ApiImportAdapter
    {
        $class = static::adapterClass($id);
        if (!$class) {
            throw new \InvalidArgumentException("Unknown API import adapter [{$id}].");
        }
        return app($class);
    }

    public static function options(): array
    {
        return Collection::make(static::all())
            ->map(fn (string $class) => [
                'id' => $class::id(),
                'label' => $class::label(),
                'preview' => $class::isPreview(),
            ])
            ->sortBy('label', SORT_NATURAL)
            ->values()
            ->all();
    }
}
