<?php

namespace App\Providers;

use App\Contracts\Communications\EmailChannelProvider;
use App\Contracts\Communications\SmsChannelProvider;
use App\Observers\Contact\ContactTriggerObserver;
use App\Services\Communications\Placeholders\DefaultPlaceholders;
use App\Services\Communications\Placeholders\DsarPlaceholders;
use App\Services\Communications\Placeholders\PlaceholderRegistry;
use App\Services\Communications\Providers\SendGridEmailProvider;
use App\Services\Communications\Providers\TwilioSmsProvider;
use Illuminate\Support\ServiceProvider;

class ContactCommunicationsServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // Singleton registry — placeholders are registered once per request.
        $this->app->singleton(PlaceholderRegistry::class, function () {
            $registry = new PlaceholderRegistry();
            DefaultPlaceholders::register($registry);
            DsarPlaceholders::register($registry);
            return $registry;
        });

        // Provider bindings — swap via container when mocking in tests.
        $this->app->bind(EmailChannelProvider::class, SendGridEmailProvider::class);
        $this->app->bind(SmsChannelProvider::class, TwilioSmsProvider::class);
    }

    public function boot(): void
    {
        // Wire MODEL_CREATED Contact Hub triggers: observe each configured model
        // so a "Record created" trigger actually fires on create. Guarded so a
        // missing/invalid class in config can't break app boot.
        foreach ((array) config('contact.trigger_observed_models', []) as $modelClass) {
            if (is_string($modelClass) && is_subclass_of($modelClass, \Illuminate\Database\Eloquent\Model::class)) {
                $modelClass::observe(ContactTriggerObserver::class);
            }
        }
    }
}
