<?php

namespace Database\Seeders;

use App\Models\AlertRule;
use App\Models\NotificationChannel;
use App\Models\Setting;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        // Bootstrap super admin. Password is for first login only — must be changed.
        User::firstOrCreate(
            ['email' => 'admin@hostseba.com'],
            [
                'name' => 'Noyon Rahman',
                'password' => Hash::make('changeme-noyon'),
                'avatar' => 'NR',
                'role' => User::ROLE_SUPER_ADMIN,
                'status' => 'active',
            ]
        );

        $this->seedNotificationChannels();
        $this->seedAlertRules();
        $this->seedSettings();
    }

    protected function seedNotificationChannels(): void
    {
        $defaults = [
            ['key' => 'email', 'name' => 'Email', 'enabled' => true],
            ['key' => 'whatsapp', 'name' => 'WhatsApp', 'enabled' => false, 'provider' => 'cloud_api'],
            ['key' => 'telegram', 'name' => 'Telegram', 'enabled' => false],
            ['key' => 'discord', 'name' => 'Discord', 'enabled' => false],
            ['key' => 'slack', 'name' => 'Slack', 'enabled' => false],
            ['key' => 'webhook', 'name' => 'Custom Webhook', 'enabled' => false],
        ];

        foreach ($defaults as $c) {
            NotificationChannel::firstOrCreate(
                ['key' => $c['key']],
                [
                    'name' => $c['name'],
                    'enabled' => $c['enabled'],
                    'provider' => $c['provider'] ?? null,
                    'verified' => false,
                    'config' => [],
                ]
            );
        }
    }

    protected function seedAlertRules(): void
    {
        $rules = [
            ['name' => 'Server Down (Any)',         'expr' => 'status = offline for > 60s', 'cfg' => ['metric' => 'status', 'op' => '=', 'value' => 'offline', 'duration' => 60], 'sev' => 'critical', 'channels' => ['email', 'telegram', 'webhook']],
            ['name' => 'High CPU Sustained',        'expr' => 'cpu > 85% for > 5m',         'cfg' => ['metric' => 'cpu', 'op' => '>', 'value' => 85, 'duration' => 300],          'sev' => 'high',     'channels' => ['telegram']],
            ['name' => 'Disk Space Critical',       'expr' => 'disk > 90%',                 'cfg' => ['metric' => 'disk', 'op' => '>', 'value' => 90, 'duration' => 0],            'sev' => 'high',     'channels' => ['email', 'telegram']],
            ['name' => 'SSL Expiring Soon',         'expr' => 'days_remaining < 14',        'cfg' => ['metric' => 'ssl_days', 'op' => '<', 'value' => 14, 'duration' => 0],       'sev' => 'medium',   'channels' => ['email']],
            ['name' => 'SSL Expired',               'expr' => 'days_remaining < 0',         'cfg' => ['metric' => 'ssl_days', 'op' => '<', 'value' => 0, 'duration' => 0],        'sev' => 'critical', 'channels' => ['email', 'telegram', 'webhook']],
            ['name' => 'Mail Queue Backlog',        'expr' => 'queue_size > 1000',          'cfg' => ['metric' => 'mail_queue', 'op' => '>', 'value' => 1000, 'duration' => 0],   'sev' => 'high',     'channels' => ['telegram']],
            ['name' => 'RBL Blacklist Detection',   'expr' => 'blacklisted = true',         'cfg' => ['metric' => 'rbl', 'op' => '=', 'value' => true, 'duration' => 0],         'sev' => 'high',     'channels' => ['email', 'telegram']],
            ['name' => 'Service Down',              'expr' => 'litespeed | mysql | dovecot = down', 'cfg' => ['metric' => 'service', 'op' => '=', 'value' => 'down', 'duration' => 0], 'sev' => 'critical', 'channels' => ['email', 'telegram', 'webhook']],
            ['name' => 'Domain Expiring',           'expr' => 'days_remaining < 30',        'cfg' => ['metric' => 'domain_days', 'op' => '<', 'value' => 30, 'duration' => 0],   'sev' => 'medium',   'channels' => ['email']],
            ['name' => 'Website Slow Response',     'expr' => 'response_time > 5000ms',     'cfg' => ['metric' => 'response_ms', 'op' => '>', 'value' => 5000, 'duration' => 60], 'sev' => 'medium',   'channels' => ['telegram']],
            ['name' => 'Port Down (Critical)',      'expr' => 'port_status = down',         'cfg' => ['metric' => 'port', 'op' => '=', 'value' => 'down', 'duration' => 0],      'sev' => 'critical', 'channels' => ['email', 'telegram', 'webhook']],
            ['name' => 'Failed Login Attempts',     'expr' => 'failed_logins > 5 in 5m',    'cfg' => ['metric' => 'failed_logins', 'op' => '>', 'value' => 5, 'duration' => 300], 'sev' => 'high',     'channels' => ['email', 'telegram']],
        ];

        foreach ($rules as $r) {
            AlertRule::firstOrCreate(
                ['name' => $r['name']],
                [
                    'trigger_expression' => $r['expr'],
                    'trigger_config' => $r['cfg'],
                    'target_scope' => 'all',
                    'severity' => $r['sev'],
                    'channels' => $r['channels'],
                    'enabled' => true,
                ]
            );
        }
    }

    protected function seedSettings(): void
    {
        Setting::set('alerts.quiet_hours', ['enabled' => true, 'start' => '23:00', 'end' => '07:00'], 'general');
        Setting::set('alerts.suppress_during_maintenance', true, 'general');
        Setting::set('alerts.group_similar', ['enabled' => true, 'window_minutes' => 5], 'general');
        Setting::set('thresholds.cpu', ['warn' => 75, 'crit' => 90], 'thresholds');
        Setting::set('thresholds.ram', ['warn' => 75, 'crit' => 90], 'thresholds');
        Setting::set('thresholds.disk', ['warn' => 80, 'crit' => 92], 'thresholds');
        Setting::set('retention.metrics_raw_days', 30, 'monitoring');
        Setting::set('retention.metrics_hourly_days', 365, 'monitoring');
        Setting::set('security.session_timeout_minutes', 120, 'security');
        Setting::set('security.require_2fa_for_admins', true, 'security');
    }
}
