<?php

declare(strict_types=1);

namespace App\Http\Controllers\Admin;

use App\Domain\Account\Models\Account;
use App\Domain\Imap\Services\DovecotService;
use App\Domain\MailBackup\Services\MailBackupService;
use App\Domain\MailDns\Services\MailDnsAutoFixer;
use App\Domain\MailHealth\Services\MailHealthChecker;
use App\Domain\MailLogs\Services\MailLogReader;
use App\Domain\MailServer\Services\MailServerFactory;
use App\Domain\SpamFilter\Services\RspamdService;
use App\Domain\Webmail\Services\WebmailFactory;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Inertia\Inertia;
use Inertia\Response;

/**
 * Mail Stack — 4 bileşenin (MTA + IMAP + Webmail + Spam) birleşik yönetimi.
 *
 * Sayfa yapisi:
 *   - /admin/mail              → Dashboard (4 component status)
 *   - /admin/mail/mta          → MailServerController'a redirect (mevcut MTA sayfasi)
 *   - /admin/mail/imap         → Dovecot management
 *   - /admin/mail/webmail      → Webmail adapter (Roundcube/SnappyMail/Rainloop)
 *   - /admin/mail/spam         → Rspamd management
 */
class MailStackController extends Controller
{
    public function __construct(
        private readonly MailServerFactory $mtaFactory,
        private readonly WebmailFactory $webmailFactory,
        private readonly DovecotService $dovecot,
        private readonly RspamdService $rspamd,
        private readonly MailHealthChecker $healthChecker,
        private readonly MailLogReader $logReader,
        private readonly MailDnsAutoFixer $dnsFixer,
        private readonly MailBackupService $mailBackup,
    ) {}

    /**
     * Mail Backup yönetim sayfası.
     */
    public function backupIndex(Request $request): Response
    {
        $totalAccounts = Schema::hasTable('accounts')
            ? Account::where('status', 'active')->whereNull('deleted_at')->count()
            : 0;

        // Son yedekler audit log'tan
        $recentBackups = $this->mailBackup->recentBackups(20);

        // Bulk stats — bugünkü başarılı yedekler
        $todayStats = ['success' => 0, 'failed' => 0, 'total' => 0];
        if (Schema::hasTable('license_audit_log')) {
            $today = DB::table('license_audit_log')
                ->where('action', 'mailbackup.completed')
                ->whereDate('occurred_at', today())
                ->selectRaw('success, count(*) as count')
                ->groupBy('success')
                ->get();
            foreach ($today as $row) {
                if ($row->success) {
                    $todayStats['success'] = (int) $row->count;
                } else {
                    $todayStats['failed'] = (int) $row->count;
                }
            }
            $todayStats['total'] = $todayStats['success'] + $todayStats['failed'];
        }

        // Restore picker: aktif hesaplar (Faz L)
        $accounts = Schema::hasTable('accounts')
            ? Account::where('status', 'active')
                ->whereNull('deleted_at')
                ->orderBy('username')
                ->limit(500)
                ->get(['id', 'username'])
                ->map(fn ($a) => ['id' => $a->id, 'username' => $a->username])
                ->all()
            : [];

        return Inertia::render('Admin/Mail/Backup', [
            'total_accounts' => $totalAccounts,
            'recent_backups' => $recentBackups,
            'today_stats' => $todayStats,
            'schedule' => $this->mailBackup->scheduleStatus(),
            'accounts' => $accounts,
            'is_windows_dev' => PHP_OS_FAMILY === 'Windows',
        ]);
    }

    /**
     * Bir hesabın snapshot listesi (Faz L) — Vue restore picker için JSON endpoint.
     */
    public function backupSnapshots(Request $request): \Illuminate\Http\JsonResponse
    {
        $data = $request->validate([
            'account_id' => 'required|integer|exists:accounts,id',
        ]);

        $account = Account::findOrFail($data['account_id']);

        return response()->json([
            'snapshots' => $this->mailBackup->listSnapshots($account),
        ]);
    }

    /**
     * Bireysel mailbox restore (Faz L).
     */
    public function backupRestoreMailbox(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'account_id' => 'required|integer|exists:accounts,id',
            'snapshot_id' => 'required|string|max:255',
            'email' => 'required|email|max:255',
        ]);

        $account = Account::findOrFail($data['account_id']);

        $result = $this->mailBackup->restoreMailbox(
            $account,
            $data['snapshot_id'],
            strtolower((string) $data['email']),
        );

        if ($result['ok']) {
            $msgs = (int) ($result['messages'] ?? 0);

            return back()->with('success', "{$data['email']} restore tamamlandı"
                . ($msgs > 0 ? " ({$msgs} mesaj)." : '.'));
        }

        return back()->with('error', 'Restore başarısız: ' . ($result['error'] ?? 'bilinmeyen hata'));
    }

    /**
     * Tüm hesapların mail'lerini yedekle (manuel trigger).
     */
    public function backupAll(): RedirectResponse
    {
        $result = $this->mailBackup->backupAll('manual');

        $message = "Mail backup tamamlandı: {$result['queued']} başarılı";
        if (count($result['errors']) > 0) {
            $message .= ', ' . count($result['errors']) . ' hata';

            return back()->with('warning', $message . '. Detay için audit log\'a bakın.');
        }

        return back()->with('success', $message);
    }

    /**
     * Tek bir hesabın mail'ini yedekle.
     */
    public function backupSingle(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'account_id' => 'required|integer|exists:accounts,id',
        ]);

        $account = Account::findOrFail($data['account_id']);
        $result = $this->mailBackup->backupAccount($account, 'manual');

        if ($result['ok']) {
            $size = round(($result['size_bytes'] ?? 0) / 1024 / 1024, 1);

            return back()->with('success', "{$account->username} mail backup: {$result['mailbox_count']} mailbox, {$size} MB");
        }

        return back()->with('error', 'Backup başarısız: ' . ($result['error'] ?? ''));
    }

    /**
     * DNS Auto-Fix — eksik MX/SPF/DMARC/DKIM kayıtlarını PowerDNS'e ekle.
     */
    public function healthAutoFix(Request $request): RedirectResponse
    {
        $hostname = (string) (parse_url(config('app.url'), PHP_URL_HOST) ?: 'panel.example.com');
        $baseDomain = preg_replace('/^[^.]+\./', '', $hostname);
        $mailHost = 'mail.' . preg_replace('/^mail\./', '', $hostname);

        $domain = $request->string('domain')->trim()->value() ?: $baseDomain;

        $result = $this->dnsFixer->fixAll($domain, $mailHost);

        $this->healthChecker->flushCache();

        if (! $result['ok']) {
            return back()->with('error', 'DNS düzeltme tamamlanamadı: ' . implode(', ', $result['errors']));
        }

        $fixedMsg = count($result['fixed']) > 0
            ? 'Eklenen kayıtlar: ' . implode(', ', $result['fixed'])
            : 'Tüm kayıtlar zaten mevcut';
        $skippedMsg = count($result['skipped']) > 0
            ? ' · Atlanan: ' . implode(', ', $result['skipped'])
            : '';

        return back()->with('success', $fixedMsg . $skippedMsg);
    }

    /**
     * Mail Logs Viewer — Postfix/Dovecot/Rspamd log tail.
     */
    public function logsIndex(Request $request): Response
    {
        $source = $request->string('source')->value() ?: 'mail';
        $search = $request->string('search')->trim()->value();
        $lines = (int) $request->integer('lines', 200);
        $lines = max(50, min(1000, $lines));

        $info = $this->logReader->info($source);
        $entries = $info['readable'] ? $this->logReader->tail($source, $lines, $search ?: null) : [];
        $stats = $info['readable'] ? $this->logReader->stats($source) : null;

        return Inertia::render('Admin/Mail/Logs', [
            'source' => $source,
            'sources' => [
                ['key' => 'mail', 'name' => 'Postfix + Dovecot (mail log)', 'icon' => 'EnvelopeIcon'],
                ['key' => 'rspamd', 'name' => 'Rspamd (spam filter)', 'icon' => 'ShieldCheckIcon'],
            ],
            'info' => $info,
            'entries' => $entries,
            'stats' => $stats,
            'filters' => [
                'search' => $search,
                'lines' => $lines,
            ],
            'is_windows_dev' => PHP_OS_FAMILY === 'Windows',
        ]);
    }

    /**
     * Mail Health Diagnostic — 5 grupta tam sağlık raporu.
     */
    public function healthIndex(Request $request): Response
    {
        $useCache = ! $request->boolean('refresh');
        $report = $this->healthChecker->check($useCache);

        return Inertia::render('Admin/Mail/Health', [
            'report' => $report,
            'is_windows_dev' => PHP_OS_FAMILY === 'Windows',
        ]);
    }

    public function healthRefresh(): RedirectResponse
    {
        $this->healthChecker->flushCache();

        return back()->with('success', 'Sağlık raporu yenilendi.');
    }

    /**
     * Test mail gönder — Health page'den admin'in kendisine.
     * Mail flow'unu uçtan uca test eder (Postfix → relay → admin mailbox).
     */
    public function healthTestMail(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'to' => 'required|email',
        ]);

        $mta = $this->mtaFactory->make();

        if (! $mta->isInstalled()) {
            return back()->with('error', 'Aktif mail sunucusu kurulu değil.');
        }

        try {
            $from = (string) (config('mail.from.address') ?: 'noreply@onox.com.tr');
            $mta->sendTestMail($data['to'], $from);

            return back()->with('success', "Test mail gönderildi: {$data['to']} (aktif MTA: {$mta->name()})");
        } catch (\Throwable $e) {
            return back()->with('error', 'Mail gönderilemedi: ' . $e->getMessage());
        }
    }

    /**
     * Mail Stack Dashboard — 4 component status overview.
     */
    public function dashboard(): Response
    {
        $mta = $this->mtaFactory->make();
        $webmail = $this->webmailFactory->make();
        $hostname = (string) (parse_url(config('app.url'), PHP_URL_HOST) ?: 'panel.example.com');

        $components = [
            [
                'key' => 'mta',
                'name' => 'Mail Transfer Agent',
                'subname' => $mta->name(),
                'description' => 'SMTP gönderme/alma — diğer mail sunucularıyla iletişim',
                'icon' => 'PaperAirplaneIcon',
                'color' => 'indigo',
                'route' => 'admin.mailserver.index',
                'config_route' => 'admin.mail.postfix.index',
                'installed' => $mta->isInstalled(),
                'running' => $mta->isInstalled() && $mta->isRunning(),
                'version' => $mta->isInstalled() ? $mta->version() : null,
            ],
            [
                'key' => 'imap',
                'name' => 'IMAP/POP3 Server',
                'subname' => $this->dovecot->name(),
                'description' => 'Müşterilerin mail client\'larıyla bağlantı (Thunderbird, Outlook, mobile)',
                'icon' => 'InboxIcon',
                'color' => 'sky',
                'route' => 'admin.mail.imap.index',
                'config_route' => 'admin.mail.dovecot.index',
                'installed' => $this->dovecot->isInstalled(),
                'running' => $this->dovecot->isInstalled() && $this->dovecot->isRunning(),
                'version' => $this->dovecot->isInstalled() ? $this->dovecot->version() : null,
            ],
            [
                'key' => 'webmail',
                'name' => 'Webmail',
                'subname' => $webmail->name(),
                'description' => 'Tarayıcı üzerinden mail erişimi (Roundcube, SnappyMail)',
                'icon' => 'GlobeAltIcon',
                'color' => 'purple',
                'route' => 'admin.mail.webmail.index',
                'config_route' => null,
                'installed' => $webmail->isInstalled() && $webmail->key() !== 'none',
                'running' => $webmail->isInstalled() && $webmail->key() !== 'none',
                'version' => $webmail->isInstalled() && $webmail->key() !== 'none' ? $webmail->version() : null,
                'access_url' => $webmail->isInstalled() && $webmail->key() !== 'none' ? $webmail->accessUrl($hostname) : null,
            ],
            [
                'key' => 'spam',
                'name' => 'Spam Filter',
                'subname' => $this->rspamd->name(),
                'description' => 'Spam/virüs taraması, DKIM/DMARC doğrulama',
                'icon' => 'ShieldCheckIcon',
                'color' => 'emerald',
                'route' => 'admin.mail.spam.index',
                'config_route' => 'admin.mail.rspamd.index',
                'installed' => $this->rspamd->isInstalled(),
                'running' => $this->rspamd->isInstalled() && $this->rspamd->isRunning(),
                'version' => $this->rspamd->isInstalled() ? $this->rspamd->version() : null,
            ],
        ];

        // Ek özellik linkleri: Health Check + Logs + DKIM + 3 config detay sayfası
        $extraLinks = [
            [
                'title' => 'Sağlık Kontrolü',
                'description' => 'Servis + Port + DNS + SSL + Test — 5-grup tam diagnostic',
                'icon' => 'HeartIcon',
                'color' => 'rose',
                'route' => 'admin.mail.health.index',
            ],
            [
                'title' => 'Mail Logları',
                'description' => 'Postfix + Dovecot + Rspamd canlı log tail + arama',
                'icon' => 'DocumentTextIcon',
                'color' => 'slate',
                'route' => 'admin.mail.logs.index',
            ],
            [
                'title' => 'Depolama Raporu',
                'description' => 'Mailbox disk kullanımı, quota uyarıları, top domain/müşteri',
                'icon' => 'ChartBarSquareIcon',
                'color' => 'purple',
                'route' => 'admin.mail.storage.index',
            ],
            [
                'title' => 'Mail Yedekleme',
                'description' => 'Tüm hesapların Maildir yedeklemesi + schedule + audit log',
                'icon' => 'CloudArrowDownIcon',
                'color' => 'emerald',
                'route' => 'admin.mail.backup.index',
            ],
            [
                'title' => 'DKIM Anahtarları',
                'description' => 'Domain bazlı DKIM signing key yönetimi',
                'icon' => 'KeyIcon',
                'color' => 'amber',
                'route' => 'admin.mail.dkim.index',
            ],
            [
                'title' => 'Postfix Konfigürasyonu',
                'description' => 'main.cf editör + queue yönetimi + restart/reload',
                'icon' => 'CogIcon',
                'color' => 'indigo',
                'route' => 'admin.mail.postfix.index',
            ],
            [
                'title' => 'Dovecot Konfigürasyonu',
                'description' => 'dovecot.conf editör + aktif oturumlar + reload',
                'icon' => 'CogIcon',
                'color' => 'sky',
                'route' => 'admin.mail.dovecot.index',
            ],
            [
                'title' => 'Rspamd Konfigürasyonu',
                'description' => 'rspamd config + Bayes train + spam/ham öğretme',
                'icon' => 'CogIcon',
                'color' => 'emerald',
                'route' => 'admin.mail.rspamd.index',
            ],
            [
                'title' => 'cPanel Mail Migration',
                'description' => 'pkgacct yedeklerinden mail hesap + forwarder içeri aktar',
                'icon' => 'ArrowDownTrayIcon',
                'color' => 'teal',
                'route' => 'admin.mail.migration.index',
            ],
            [
                'title' => 'E-posta Listeleri',
                'description' => 'Toplu duyuru için adres listesi yönetimi (Mailman muadili)',
                'icon' => 'UserGroupIcon',
                'color' => 'fuchsia',
                'route' => 'admin.mail.mailing-lists.index',
            ],
        ];

        // Genel sağlık: tüm component'lar çalışıyor mu
        $allRunning = collect($components)->every(fn ($c) => $c['running']);
        $someInstalled = collect($components)->some(fn ($c) => $c['installed']);
        $health = $allRunning ? 'healthy' : ($someInstalled ? 'partial' : 'not_configured');

        // Spam stats (varsa)
        $spamStats = $this->rspamd->isInstalled() ? $this->rspamd->stats() : null;

        // Mail queue (MTA varsa)
        $mtaQueue = $mta->isInstalled() ? $mta->queueStatus() : null;

        // Dovecot connections (varsa)
        $imapConnections = $this->dovecot->isInstalled() ? $this->dovecot->activeConnections() : null;

        $recentAudit = Schema::hasTable('license_audit_log')
            ? DB::table('license_audit_log')
                ->where(function ($q) {
                    $q->where('action', 'like', 'mailserver.%')
                      ->orWhere('action', 'like', 'webmail.%')
                      ->orWhere('action', 'like', 'imap.%')
                      ->orWhere('action', 'like', 'spam.%');
                })
                ->orderByDesc('id')
                ->limit(15)
                ->get()
            : collect();

        // Customer email account istatistikleri
        $emailStats = [
            'total_accounts' => Schema::hasTable('email_accounts') ? DB::table('email_accounts')->count() : 0,
            'total_forwarders' => Schema::hasTable('email_forwarders') ? DB::table('email_forwarders')->count() : 0,
            'total_autoresponders' => Schema::hasTable('email_autoresponders') ? DB::table('email_autoresponders')->count() : 0,
        ];

        return Inertia::render('Admin/Mail/Dashboard', [
            'components' => $components,
            'extra_links' => $extraLinks,
            'health' => $health,
            'spam_stats' => $spamStats,
            'mta_queue' => $mtaQueue,
            'imap_connections' => $imapConnections,
            'email_stats' => $emailStats,
            'recent_audit' => $recentAudit,
            'is_windows_dev' => PHP_OS_FAMILY === 'Windows',
            'hostname' => $hostname,
        ]);
    }

    // ─── Webmail ───────────────────────────────────────────────────────────

    public function webmailIndex(): Response
    {
        $adapters = $this->webmailFactory->listAll();
        $active = $this->webmailFactory->make();
        $hostname = (string) (parse_url(config('app.url'), PHP_URL_HOST) ?: 'panel.example.com');

        return Inertia::render('Admin/Mail/Webmail', [
            'adapters' => $adapters,
            'active_key' => $this->webmailFactory->activeKey(),
            'active_name' => $active->name(),
            'active_installed' => $active->isInstalled() && $active->key() !== 'none',
            'active_version' => $active->isInstalled() && $active->key() !== 'none' ? $active->version() : null,
            'active_url' => $active->isInstalled() && $active->key() !== 'none' ? $active->accessUrl($hostname) : null,
            'active_admin_url' => $active->isInstalled() && $active->key() !== 'none' ? $active->adminUrl($hostname) : null,
            'hostname' => $hostname,
            'is_windows_dev' => PHP_OS_FAMILY === 'Windows',
        ]);
    }

    public function webmailInstall(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'driver' => 'required|string|in:' . implode(',', $this->webmailFactory->supportedDrivers()),
        ]);

        $adapter = $this->webmailFactory->makeByKey($data['driver']);
        if (! $adapter) {
            return back()->with('error', 'Bilinmeyen driver.');
        }

        if ($adapter->isInstalled() && $data['driver'] !== 'none') {
            return back()->with('warning', $adapter->name() . ' zaten kurulu.');
        }

        $result = $adapter->install();
        $this->audit('webmail.install', $data['driver'], $result['ok']);

        return $result['ok']
            ? back()->with('success', $adapter->name() . ' kuruldu. URL: ' . $adapter->urlPath())
            : back()->with('error', 'Kurulum başarısız: ' . ($result['error'] ?? ''));
    }

    public function webmailUninstall(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'driver' => 'required|string|in:' . implode(',', $this->webmailFactory->supportedDrivers()),
        ]);

        $adapter = $this->webmailFactory->makeByKey($data['driver']);
        $result = $adapter->uninstall();
        $this->audit('webmail.uninstall', $data['driver'], $result['ok']);

        return $result['ok']
            ? back()->with('success', $adapter->name() . ' kaldırıldı.')
            : back()->with('error', 'Kaldırma başarısız.');
    }

    public function webmailSwitch(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'driver' => 'required|string|in:' . implode(',', $this->webmailFactory->supportedDrivers()),
        ]);

        $adapter = $this->webmailFactory->makeByKey($data['driver']);
        if (! $adapter->isInstalled() && $data['driver'] !== 'none') {
            return back()->with('warning', $adapter->name() . ' kurulu değil. Önce kurun.');
        }

        $this->persistWebmailDriver($data['driver']);
        $this->audit('webmail.switch', $data['driver'], true);

        return back()->with('success', 'Aktif webmail: ' . $adapter->name());
    }

    // ─── IMAP / Dovecot ────────────────────────────────────────────────────

    public function imapIndex(): Response
    {
        $hostname = (string) (parse_url(config('app.url'), PHP_URL_HOST) ?: 'panel.example.com');

        return Inertia::render('Admin/Mail/Imap', [
            'name' => $this->dovecot->name(),
            'description' => $this->dovecot->description(),
            'strengths' => $this->dovecot->strengths(),
            'installed' => $this->dovecot->isInstalled(),
            'running' => $this->dovecot->isInstalled() && $this->dovecot->isRunning(),
            'enabled' => $this->dovecot->isInstalled() && $this->dovecot->isEnabled(),
            'version' => $this->dovecot->isInstalled() ? $this->dovecot->version() : null,
            'ports' => $this->dovecot->ports(),
            'connections' => $this->dovecot->isInstalled() ? $this->dovecot->activeConnections() : null,
            'hostname' => $hostname,
            'is_windows_dev' => PHP_OS_FAMILY === 'Windows',
        ]);
    }

    public function imapInstall(): RedirectResponse
    {
        $result = $this->dovecot->install();
        $this->audit('imap.install', 'dovecot', $result['ok']);

        return $result['ok']
            ? back()->with('success', 'Dovecot kuruldu. IMAP/POP3 servisleri aktif.')
            : back()->with('error', 'Kurulum başarısız: ' . ($result['error'] ?? ''));
    }

    public function imapAction(Request $request, string $action): RedirectResponse
    {
        $allowed = ['start', 'stop', 'restart', 'reload', 'enable', 'disable'];
        if (! in_array($action, $allowed, true)) {
            return back()->with('error', 'Geçersiz eylem.');
        }

        if (! $this->dovecot->isInstalled() && ! in_array($action, ['enable', 'disable'], true)) {
            return back()->with('error', 'Dovecot kurulu değil.');
        }

        try {
            $this->dovecot->{$action}();
            $this->audit("imap.{$action}", 'dovecot', true);

            $labels = ['start' => 'başlatıldı', 'stop' => 'durduruldu', 'restart' => 'restart',
                'reload' => 'reload', 'enable' => 'enable', 'disable' => 'disable'];

            return back()->with('success', 'Dovecot ' . ($labels[$action] ?? $action));
        } catch (\Throwable $e) {
            return back()->with('error', $action . ' başarısız: ' . $e->getMessage());
        }
    }

    // ─── Spam Filter / Rspamd ──────────────────────────────────────────────

    public function spamIndex(): Response
    {
        $hostname = (string) (parse_url(config('app.url'), PHP_URL_HOST) ?: 'panel.example.com');

        return Inertia::render('Admin/Mail/Spam', [
            'name' => $this->rspamd->name(),
            'description' => $this->rspamd->description(),
            'strengths' => $this->rspamd->strengths(),
            'installed' => $this->rspamd->isInstalled(),
            'running' => $this->rspamd->isInstalled() && $this->rspamd->isRunning(),
            'enabled' => $this->rspamd->isInstalled() && $this->rspamd->isEnabled(),
            'version' => $this->rspamd->isInstalled() ? $this->rspamd->version() : null,
            'stats' => $this->rspamd->isInstalled() ? $this->rspamd->stats() : null,
            'web_ui_url' => $this->rspamd->isInstalled() ? $this->rspamd->webUiUrl($hostname) : null,
            'is_windows_dev' => PHP_OS_FAMILY === 'Windows',
        ]);
    }

    public function spamInstall(): RedirectResponse
    {
        $result = $this->rspamd->install();
        $this->audit('spam.install', 'rspamd', $result['ok']);

        return $result['ok']
            ? back()->with('success', 'Rspamd kuruldu + Postfix\'e bağlandı. Web UI: port 11334')
            : back()->with('error', 'Kurulum başarısız: ' . ($result['error'] ?? ''));
    }

    public function spamAction(Request $request, string $action): RedirectResponse
    {
        $allowed = ['start', 'stop', 'restart', 'reload', 'enable', 'disable'];
        if (! in_array($action, $allowed, true)) {
            return back()->with('error', 'Geçersiz eylem.');
        }

        if (! $this->rspamd->isInstalled() && ! in_array($action, ['enable', 'disable'], true)) {
            return back()->with('error', 'Rspamd kurulu değil.');
        }

        try {
            $this->rspamd->{$action}();
            $this->audit("spam.{$action}", 'rspamd', true);

            return back()->with('success', 'Rspamd ' . $action);
        } catch (\Throwable $e) {
            return back()->with('error', $action . ' başarısız: ' . $e->getMessage());
        }
    }

    // ─── Helpers ───────────────────────────────────────────────────────────

    private function persistWebmailDriver(string $driver): void
    {
        if (Schema::hasTable('server_settings')) {
            DB::table('server_settings')->updateOrInsert(
                ['key' => 'webmail_driver'],
                [
                    'group' => 'webmail',
                    'type' => 'string',
                    'value' => $driver,
                    'updated_at' => now(),
                    'created_at' => now(),
                ]
            );
        }
        try {
            \Artisan::call('config:clear');
        } catch (\Throwable) {}
    }

    private function audit(string $action, ?string $driver, bool $success): void
    {
        try {
            if (Schema::hasTable('license_audit_log')) {
                DB::table('license_audit_log')->insert([
                    'action' => $action,
                    'payload' => json_encode(['driver' => $driver], JSON_UNESCAPED_UNICODE),
                    'success' => $success,
                    'remote_ip' => request()?->ip(),
                    'occurred_at' => now(),
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }
        } catch (\Throwable) {}
    }
}
