<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class FormEscalationRule extends Model
{
    protected $fillable = [
        'form_id', 'trigger_type', 'trigger_config',
        'action_type', 'action_config', 'is_active',
    ];

    protected $casts = [
        'trigger_config' => 'array',
        'action_config' => 'array',
        'is_active' => 'boolean',
    ];

    public function form()
    {
        return $this->belongsTo(Form::class);
    }

    /**
     * Check if this rule should fire for a given submission.
     */
    public function shouldTrigger(FormSubmission $submission): bool
    {
        if (!$this->is_active) return false;

        return match ($this->trigger_type) {
            'sla_breach' => $submission->is_sla_breached,
            'field_value' => $this->checkFieldValue($submission),
            default => false,
        };
    }

    protected function checkFieldValue(FormSubmission $submission): bool
    {
        $config = $this->trigger_config;
        $fieldValue = $submission->data[$config['field_key']] ?? null;
        $targetValue = $config['value'] ?? null;
        $operator = $config['operator'] ?? 'equals';

        return match ($operator) {
            'equals' => $fieldValue == $targetValue,
            'not_equals' => $fieldValue != $targetValue,
            'contains' => str_contains((string)$fieldValue, (string)$targetValue),
            default => false,
        };
    }

    /**
     * Execute the escalation action on a submission/task.
     */
    public function execute(FormSubmission $submission): void
    {
        $config = $this->action_config;
        $task = $submission->task;

        match ($this->action_type) {
            'reassign' => $task?->update(['assignee_id' => $config['user_id'] ?? null]),
            'change_priority' => $task?->update(['priority' => $config['priority'] ?? 'high']),
            'notify' => $this->sendNotification($submission, $config),
            default => null,
        };
    }

    protected function sendNotification(FormSubmission $submission, array $config): void
    {
        if (empty($config['user_id'])) return;
        \App\Models\User::find($config['user_id'])?->notify(
            new \Illuminate\Notifications\Messages\DatabaseMessage([
                'title' => 'Form Escalation: ' . $submission->form->title,
                'message' => $config['notification_message'] ?? 'A form submission requires attention.',
                'url' => route('form-builder.submission.show', [$submission->form_id, $submission->id]),
            ])
        );
    }
}
