<?php

namespace RTMMailComposer\ContextBuilder;

use RTMMailComposer\Model\CustomMail;
use WordpressModels\Traits\SingletonTrait;

class ContextBuilderRegistry
{

    use SingletonTrait;

    /**
     * @var array{string: ContextBuilderInterface[]}
     */
    private array $builders = [];


    /**
     * Register object builder to the current context builder
     * @param ContextBuilderInterface $builder
     *
     * @return void
     */
    public function registerContextBuilder(ContextBuilderInterface $builder)
    {
        $this->builders[$builder->getSubject()][] = $builder;
    }

    public function prepareContext(CustomMail $mail, $mailObject, array $context = []): array
    {
        return array_merge(
            ...array_map(
            fn($builder) => $builder->prepareContext($mail, $mailObject, $context),
            [
                ...($this->builders["object/{$mail->getObjectType()}"] ?? []),
                ...($this->builders["recipient/{$mail->getRecipientType()}"] ?? [])
            ]));
    }
}
