<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Workflow extends Model
{
    protected $fillable = [
        'name',
        'description',
        'trigger_event',
        'is_active',
        'priority',
        'execution_count',
        'last_executed_at',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'last_executed_at' => 'datetime',
    ];

    public function logs()
    {
        return $this->hasMany(WorkflowLog::class)->orderByDesc('created_at');
    }

    public function nodes(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany(WorkflowNode::class);
    }

    public function edges(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany(WorkflowEdge::class);
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeForEvent($query, string $event)
    {
        return $query->where('trigger_event', $event);
    }

    /**
     * Supported trigger events.
     */
    public static function getTriggerEvents(): array
    {
        return [
            'invoice.created' => 'Invoice Created',
            'invoice.paid' => 'Invoice Paid',
            'invoice.overdue' => 'Invoice Overdue',
            'ticket.opened' => 'Ticket Opened',
            'ticket.replied' => 'Ticket Replied',
            'ticket.closed' => 'Ticket Closed',
            'service.created' => 'Service Created',
            'service.activated' => 'Service Activated',
            'service.suspended' => 'Service Suspended',
            'service.terminated' => 'Service Terminated',
            'client.registered' => 'Client Registered',
            'order.placed' => 'Order Placed',
            'order.completed' => 'Order Completed',
        ];
    }

    /**
     * Supported action types.
     */
    public static function getActionTypes(): array
    {
        return [
            'send_email' => 'Send Email',
            'send_sms' => 'Send SMS',
            'suspend_service' => 'Suspend Service',
            'unsuspend_service' => 'Unsuspend Service',
            'terminate_service' => 'Terminate Service',
            'create_ticket' => 'Create Ticket',
            'add_note' => 'Add Note',
            'notify_admin' => 'Notify Admin',
            'change_status' => 'Change Status',
            'wait' => 'Wait (Delay)',
        ];
    }
}
