<?php

/**
 * app/Models/AlertRule.php
 *
 * Model for access to alert_rules table data
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * @link       https://www.librenms.org
 *
 * @copyright  2016 Neil Lathwood
 * @author     Neil Lathwood <neil@lathwood.co.uk>
 */

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Gate;
use LibreNMS\Enum\AlertState;

/**
 * @property int $id
 * @property string $name
 * @property string $severity
 * @property array<string, mixed>|null $extra
 * @property bool|int $disabled
 * @property string|null $proc
 * @property string|null $notes
 * @property string $query
 * @property array<string, mixed>|null $builder
 * @property bool|int $invert_map
 * @property int|null $alert_operation_id
 * @property AlertOperation|null $alertOperation
 */
class AlertRule extends BaseModel
{
    use HasFactory;

    public $timestamps = false;

    protected static function booted(): void
    {
        static::deleting(function (AlertRule $rule): void {
            $rule->alerts()->delete();
            $rule->logs()->delete();
            $rule->templateMaps()->delete();

            $rule->devices()->detach();
            $rule->groups()->detach();
            $rule->locations()->detach();
        });
    }

    protected $fillable = [
        'severity',
        'extra',
        'disabled',
        'name',
        'proc',
        'notes',
        'query',
        'builder',
        'invert_map',
        'alert_operation_id',
    ];

    protected $casts = [
        'builder' => 'array',
        'extra' => 'array',
        'alert_operation_id' => 'integer',
    ];

    // ---- Query scopes ----

    /**
     * @param  Builder<AlertRule>  $query
     * @return Builder
     */
    public function scopeEnabled($query)
    {
        return $query->where('alert_rules.disabled', 0);
    }

    /**
     * Scope for only alert rules that are currently in alarm
     *
     * @param  Builder<AlertRule>  $query
     * @return Builder
     */
    public function scopeIsActive($query)
    {
        return $query->enabled()
            ->join('alerts', 'alerts.rule_id', 'alert_rules.id')
            ->whereNotIn('alerts.state', [AlertState::CLEAR, AlertState::ACKNOWLEDGED, AlertState::RECOVERED]);
    }

    /**
     * Scope to filter rules for devices permitted to user
     * (do not use for admin and global read-only users)
     *
     * @param  Builder<AlertRule>  $query
     * @param  User  $user
     * @return mixed
     */
    public function scopeHasAccess($query, User $user)
    {
        if (Gate::allows('viewAll', AlertRule::class)) {
            return $query;
        }

        if (! $this->isJoined($query, 'alerts')) {
            $query->join('alerts', 'alerts.rule_id', 'alert_rules.id');
        }

        return $this->hasDeviceAccess($query, $user, 'alerts');
    }

    // ---- Define Relationships ----

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany<\App\Models\Alert, $this>
     */
    public function alerts(): HasMany
    {
        return $this->hasMany(Alert::class, 'rule_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany<\App\Models\AlertLog, $this>
     */
    public function logs(): HasMany
    {
        return $this->hasMany(AlertLog::class, 'rule_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany<\App\Models\AlertTemplateMap, $this>
     */
    public function templateMaps(): HasMany
    {
        return $this->hasMany(AlertTemplateMap::class, 'alert_rule_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany<\App\Models\Device, $this>
     */
    public function devices(): BelongsToMany
    {
        return $this->belongsToMany(Device::class, 'alert_device_map', 'rule_id', 'device_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany<\App\Models\DeviceGroup, $this>
     */
    public function groups(): BelongsToMany
    {
        return $this->belongsToMany(DeviceGroup::class, 'alert_group_map', 'rule_id', 'group_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany<\App\Models\Location, $this>
     */
    public function locations(): BelongsToMany
    {
        return $this->belongsToMany(Location::class, 'alert_location_map', 'rule_id');
    }

    /**
     * @return BelongsTo<AlertOperation, $this>
     */
    public function alertOperation(): BelongsTo
    {
        return $this->belongsTo(AlertOperation::class, 'alert_operation_id');
    }

    /**
     * Backwards-compatible shape: one array entry per segment (same as legacy multi-row operations).
     *
     * @return array<int, array<string, mixed>>
     */
    public function toOperationsApiArray(): array
    {
        $this->load([
            'alertOperation.segments.transportSingles:alert_transports.transport_id,transport_type,transport_name',
            'alertOperation.segments.transportGroups:alert_transport_groups.transport_group_id,transport_group_name',
        ]);

        if ($this->alertOperation === null) {
            return [];
        }

        $out = [];
        foreach ($this->alertOperation->segments as $segment) {
            $out[] = array_merge($segment->toApiArray(), [
                'alert_operation_id' => $this->alertOperation->id,
                'name' => $this->alertOperation->name,
            ]);
        }

        return $out;
    }
}
