<?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\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class EmailMonitor extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name', 'host', 'smtp_port', 'ports',
        'status', 'port_status', 'queue_size', 'queue_size_threshold',
        'blacklisted_on', 'bounce_rate',
        'spf_valid', 'dkim_valid', 'dmarc_valid',
        'last_checked_at', 'status_changed_at', 'uptime_percent_30d',
        'server_id', 'is_active', 'alerts_enabled',
        // Check behaviour
        'timeout_seconds', 'check_interval_seconds', 'max_retries',
        'triggering_locations_min',
        // Alerting policy
        'alert_after_downtime_minutes',
        'repeat_alert_times', 'repeat_alert_interval_minutes',
        'location_fails_threshold_x', 'location_fails_window_y',
        // SMTP-specific verifications
        'verify_ssl', 'verify_smtp_auth', 'public_report',
        // Probe-location restriction (array of probe_location codes)
        'monitor_from_location_codes',
    ];

    protected $casts = [
        'ports' => 'array',
        'port_status' => 'array',
        'blacklisted_on' => 'array',
        'spf_valid' => 'boolean',
        'dkim_valid' => 'boolean',
        'dmarc_valid' => 'boolean',
        'is_active' => 'boolean',
        'alerts_enabled' => 'boolean',
        'last_checked_at' => 'datetime',
        'status_changed_at' => 'datetime',
        'bounce_rate' => 'decimal:2',
        'uptime_percent_30d' => 'decimal:2',
        // Advanced fields
        'verify_ssl' => 'boolean',
        'verify_smtp_auth' => 'boolean',
        'public_report' => 'boolean',
        'monitor_from_location_codes' => 'array',
    ];

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

    public function incidents(): MorphMany
    {
        return $this->morphMany(Incident::class, 'subject');
    }
}
