<?php

namespace App\Models;

/**
 * See CreateAiAlertsTable's migration comment. Written only by
 * FlagAnomalies (App\Commands\FlagAnomalies); the manager-facing alerts
 * list only ever reads and dismisses.
 */
class AiAlertModel extends TenantModel
{
    protected $table            = 'ai_alerts';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useTimestamps    = true;
    protected $createdField     = 'created_at';
    protected $updatedField     = '';

    protected $allowedFields = [
        'alert_date',
        'title',
        'description',
        'severity',
        'data_snapshot',
        'dismissed_at',
        'dismissed_by',
    ];

    public function open(): array
    {
        return $this->where('dismissed_at', null)->orderBy('created_at', 'desc')->findAll();
    }

    public function countOpen(): int
    {
        return $this->where('dismissed_at', null)->countAllResults();
    }

    public function dismiss(int $id, int $userId): bool
    {
        return $this->update($id, ['dismissed_at' => date('Y-m-d H:i:s'), 'dismissed_by' => $userId]);
    }
}
