<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class AlertRule extends Model
{
    use HasFactory;

    protected $fillable = [
        'client_id',
        'platform',
        'name',
        'metric',
        'operator',
        'threshold',
        'period',
        'severity',
        'notification_channels',
        'notification_emails',
        'cooldown_minutes',
        'last_evaluated_at',
        'last_triggered_at',
        'last_value',
        'last_status',
        'meta',
        'is_active',
    ];

    protected $casts = [
        'threshold' => 'decimal:4',
        'notification_channels' => 'array',
        'notification_emails' => 'array',
        'cooldown_minutes' => 'integer',
        'last_evaluated_at' => 'datetime',
        'last_triggered_at' => 'datetime',
        'last_value' => 'decimal:6',
        'meta' => 'array',
        'is_active' => 'boolean',
    ];

    public function client(): BelongsTo
    {
        return $this->belongsTo(Client::class);
    }

    public function logs(): HasMany
    {
        return $this->hasMany(AlertLog::class);
    }

    public function hasChannel(string $channel): bool
    {
        return in_array($channel, $this->notification_channels ?: [], true);
    }

    public function isInCooldown(): bool
    {
        if (! $this->last_triggered_at || ! $this->cooldown_minutes) {
            return false;
        }

        return $this->last_triggered_at->addMinutes($this->cooldown_minutes)->isFuture();
    }
}
