<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;use App\Models\Concerns\BelongsToCompany;


class AutomationRule extends Model
{
    use BelongsToCompany;
    protected $fillable = ['name','description','trigger','conditions','actions','active','order'];
    protected function casts(): array {
        return ['conditions'=>'array','actions'=>'array','active'=>'boolean'];
    }

    public static array $triggers = [
        'ticket_created'  => 'Ticket creado',
        'ticket_updated'  => 'Ticket actualizado',
        'status_changed'  => 'Estado cambiado',
        'sla_warning'     => 'SLA próximo a vencer (2h)',
        'sla_breached'    => 'SLA incumplido',
        'ticket_idle'     => 'Ticket sin actividad (24h)',
    ];

    public static array $conditionFields = [
        'priority'    => 'Prioridad',
        'category'    => 'Categoría',
        'status'      => 'Estado',
        'type'        => 'Tipo',
        'department'  => 'Departamento',
        'requester'   => 'Solicitante (rol)',
        'has_assignee'=> 'Tiene agente asignado',
    ];

    public static array $operators = [
        'equals'     => 'es igual a',
        'not_equals' => 'no es igual a',
        'contains'   => 'contiene',
        'is_empty'   => 'está vacío',
        'is_not_empty'=> 'no está vacío',
    ];

    public static array $actionTypes = [
        'assign_agent'       => 'Asignar agente',
        'assign_group'       => 'Asignar grupo',
        'change_priority'    => 'Cambiar prioridad',
        'change_status'      => 'Cambiar estado',
        'add_tag'            => 'Agregar etiqueta',
        'send_notification'  => 'Enviar notificación interna',
        'add_comment'        => 'Agregar comentario automático',
        'escalate'           => 'Escalar a supervisor',
    ];

    public function logs(): HasMany { return $this->hasMany(AutomationLog::class, 'rule_id'); }

    public function scopeActive($q)  { return $q->where('active', true)->orderBy('order'); }
    public function scopeForTrigger($q, string $trigger) { return $q->active()->where('trigger', $trigger); }
}
