<?php

namespace EasyLinkAutomations\Auth;

if (!defined('ABSPATH')) {
    exit;
}

use EasyLinkAutomations\Auth\Contracts\PlatformAuthInterface;

/**
 * Registry for managing platform auth definitions.
 *
 * Platforms register their auth schemas here so they can be discovered
 * by the connection UI and used during credential authentication.
 */
final class PlatformAuthRegistry
{
    /**
     * @var array<string, class-string<PlatformAuthInterface>>
     */
    private static array $platforms = [];

    /**
     * Register a platform auth class.
     *
     * @param class-string<PlatformAuthInterface> $platformClass
     */
    public static function register(string $platformClass): void
    {
        if (!is_subclass_of($platformClass, PlatformAuthInterface::class)) {
            return;
        }

        $slug = $platformClass::getSlug();
        self::$platforms[$slug] = $platformClass;
    }

    /**
     * Get a platform auth class by slug.
     *
     * @return class-string<PlatformAuthInterface>|null
     */
    public static function get(string $slug): ?string
    {
        return self::$platforms[$slug] ?? null;
    }

    /**
     * Check if a platform is registered.
     */
    public static function has(string $slug): bool
    {
        return isset(self::$platforms[$slug]);
    }

    /**
     * Get all registered platform slugs.
     *
     * @return array<string>
     */
    public static function slugs(): array
    {
        return array_keys(self::$platforms);
    }

    /**
     * Get all platforms as serialized arrays (for API response).
     *
     * @return array<int, array>
     */
    public static function toArray(): array
    {
        $result = [];

        foreach (self::$platforms as $class) {
            $result[] = $class::toArray();
        }

        return $result;
    }

    /**
     * Get platforms grouped by auth type.
     *
     * @return array<string, array>
     */
    public static function groupedByAuthType(): array
    {
        $grouped = [];

        foreach (self::$platforms as $class) {
            $authType = $class::getAuthType();
            $grouped[$authType][] = $class::toArray();
        }

        return $grouped;
    }
}
