<?php

namespace App\Models\Contact;

use App\Enum\Contact\TemplateTriggerType;
use App\Trait\BelongsToSolicitor;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ContactTemplateTrigger extends Model
{
    use BelongsToSolicitor;

    protected $table = 'contact_template_triggers';

    protected $fillable = [
        'contact_template_id',
        'solicitor_id',
        'trigger_type',
        'model_type',
        'conditions',
        'dedupe_window_minutes',
        'is_active',
    ];

    protected $casts = [
        'trigger_type' => TemplateTriggerType::class,
        'conditions' => 'array',
        'is_active' => 'boolean',
        'dedupe_window_minutes' => 'integer',
    ];

    public function template(): BelongsTo
    {
        return $this->belongsTo(ContactTemplate::class, 'contact_template_id');
    }

    public function matchesConditions(array $context): bool
    {
        if (empty($this->conditions)) {
            return true;
        }

        foreach ($this->conditions as $key => $expected) {
            $actual = $context[$key] ?? null;

            if (is_array($expected)) {
                if (!in_array($actual, $expected, false)) {
                    return false;
                }
            } elseif ((string) $actual !== (string) $expected) {
                return false;
            }
        }

        return true;
    }
}
