<?php

namespace App\Services\DecisionEvents;

use App\Services\DecisionEvents\Contracts\DecisionEventHandler;
use App\Services\DecisionEvents\Handlers\AddSegmentHandler;
use InvalidArgumentException;

class Registry
{
    /**
     * Map of event keys to handler classes.
     *
     * @var array<string, class-string<DecisionEventHandler>>
     */
    protected static array $map = [
        'add_segment' => AddSegmentHandler::class,
        'archive_contract' => \App\Services\DecisionEvents\Handlers\ArchiveContractHandler::class,
        'end_field_job' => \App\Services\DecisionEvents\Handlers\EndFieldJobHandler::class,
        'add_call_later' => \App\Services\DecisionEvents\Handlers\CallLaterHandler::class,
    ];

    public static function resolve(string $key): DecisionEventHandler
    {
        $key = trim(strtolower($key));
        $class = static::$map[$key] ?? null;
        if (! $class) {
            throw new InvalidArgumentException("Unknown decision event handler for key: {$key}");
        }
        if (! class_exists($class)) {
            throw new InvalidArgumentException("Handler class {$class} for key {$key} does not exist (check autoload)");
        }
        $handler = app($class);
        if (! $handler instanceof DecisionEventHandler) {
            throw new InvalidArgumentException("Handler for key {$key} must implement DecisionEventHandler");
        }

        return $handler;
    }
}
