<?php

namespace App\Campaigns\Platforms;

use App\Models\Campaign;
use Illuminate\Contracts\Container\Container;
use InvalidArgumentException;

/**
 * Every platform the product knows about.
 *
 * One lookup, so nothing else needs a list of platforms or a match statement
 * over them. Adding a platform is a class plus a config line.
 */
class Platforms
{
    public function __construct(private readonly Container $container) {}

    public function for(Campaign|string $platform): PlatformRules
    {
        $key = $platform instanceof Campaign ? (string) $platform->platform : $platform;
        $class = config("platforms.rules.{$key}");

        if (! $class) {
            throw new InvalidArgumentException(
                "[{$key}] is not a platform this product supports. Supported: ".implode(', ', $this->keys())
            );
        }

        return $this->container->make($class);
    }

    public function supports(?string $key): bool
    {
        return $key !== null && config("platforms.rules.{$key}") !== null;
    }

    /** @return list<string> */
    public function keys(): array
    {
        return array_keys((array) config('platforms.rules', []));
    }

    /** @return list<PlatformRules> */
    public function all(): array
    {
        return array_map(fn (string $key): PlatformRules => $this->for($key), $this->keys());
    }
}
