<?php

namespace App\Observers\Contact;

use App\Actions\Communications\EvaluateContactTriggersAction;
use App\Enum\Contact\TemplateTriggerType;
use Illuminate\Database\Eloquent\Model;

/**
 * Fires Contact Hub MODEL_CREATED triggers when an observed model is created.
 *
 * Registered against each class listed in config('contact.trigger_observed_models')
 * by ContactCommunicationsServiceProvider. The model's raw attributes are passed as
 * the condition-matching context so triggers can filter on fields (e.g. solicitor_id,
 * redress_type) via ContactTemplateTrigger::matchesConditions().
 */
class ContactTriggerObserver
{
    public function created(Model $model): void
    {
        // Mirror the inline dispatch pattern in HasStatus/HasTags: never let a
        // trigger failure bubble up and abort the create that caused it.
        try {
            app(EvaluateContactTriggersAction::class)(
                $model,
                TemplateTriggerType::MODEL_CREATED,
                $model->getAttributes(),
            );
        } catch (\Throwable $e) {
            logger()->error('Contact trigger evaluation failed on model create', [
                'subject' => $model::class,
                'subject_id' => $model->getKey(),
                'error' => $e->getMessage(),
            ]);
        }
    }
}
