<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AlertLog;
use App\Models\AlertRule;
use App\Models\Client;
use App\Services\Alerts\AlertEngine;
use App\Services\Alerts\AlertMetricCatalog;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AlertRuleController extends Controller
{
    public function index(): View
    {
        $page_title = 'Uyarı Kuralları';
        $page_description = 'Harcama, performans, SEO ve sistem uyarıları';
        $rules = AlertRule::with('client')->withCount(['logs as open_logs_count' => fn ($query) => $query->where('status', 'open')])->latest()->paginate(20);
        $openAlertCount = AlertLog::where('status', 'open')->count();

        return view('admin.alerts.index', compact('page_title', 'page_description', 'rules', 'openAlertCount'));
    }

    public function create(): View
    {
        $page_title = 'Uyarı Kuralı Ekle';
        $page_description = 'Yeni performans uyarısı tanımla';
        $clients = Client::orderBy('company_name')->get();
        $metricCatalog = AlertMetricCatalog::all();
        $rule = new AlertRule([
            'platform' => 'google_ads',
            'metric' => 'cost',
            'operator' => '>',
            'period' => 'daily',
            'severity' => 'warning',
            'notification_channels' => ['email', 'panel'],
            'cooldown_minutes' => 1440,
            'is_active' => true,
        ]);

        return view('admin.alerts.create', compact('page_title', 'page_description', 'clients', 'rule', 'metricCatalog'));
    }

    public function store(Request $request): RedirectResponse
    {
        AlertRule::create($this->validated($request));

        return redirect()->route('admin.alert-rules.index')->with('success', 'Uyarı kuralı oluşturuldu.');
    }

    public function show(AlertRule $alertRule): View
    {
        $page_title = $alertRule->name;
        $page_description = 'Uyarı kuralı detayı';
        $alertRule->load('client');
        $logs = $alertRule->logs()->with('client')->latest('triggered_at')->paginate(20);

        return view('admin.alerts.show', compact('page_title', 'page_description', 'alertRule', 'logs'));
    }

    public function edit(AlertRule $alertRule): View
    {
        $page_title = 'Uyarı Kuralı Düzenle';
        $page_description = $alertRule->name;
        $clients = Client::orderBy('company_name')->get();
        $metricCatalog = AlertMetricCatalog::all();
        $rule = $alertRule;

        return view('admin.alerts.edit', compact('page_title', 'page_description', 'clients', 'rule', 'metricCatalog'));
    }

    public function update(Request $request, AlertRule $alertRule): RedirectResponse
    {
        $alertRule->update($this->validated($request));

        return redirect()->route('admin.alert-rules.index')->with('success', 'Uyarı kuralı güncellendi.');
    }

    public function destroy(AlertRule $alertRule): RedirectResponse
    {
        $alertRule->delete();

        return redirect()->route('admin.alert-rules.index')->with('success', 'Uyarı kuralı silindi.');
    }

    public function evaluate(AlertRule $alertRule, AlertEngine $engine): RedirectResponse
    {
        $summary = $engine->evaluateAll(ruleId: $alertRule->id);

        return back()->with('success', 'Kural çalıştırıldı. Tetiklenen uyarı: ' . $summary['triggered']);
    }

    public function evaluateAll(AlertEngine $engine): RedirectResponse
    {
        $summary = $engine->evaluateAll();

        return back()->with('success', 'Tüm aktif kurallar çalıştırıldı. Tetiklenen uyarı: ' . $summary['triggered']);
    }

    public function logs(Request $request): View
    {
        $page_title = 'Uyarı Geçmişi';
        $page_description = 'Tetiklenen performans, SEO ve sistem uyarıları';
        $clients = Client::orderBy('company_name')->get();

        $logs = AlertLog::with(['client', 'rule'])
            ->when($request->filled('client_id'), fn ($query) => $query->where('client_id', $request->integer('client_id')))
            ->when($request->filled('platform'), fn ($query) => $query->where('platform', $request->string('platform')))
            ->when($request->filled('severity'), fn ($query) => $query->where('severity', $request->string('severity')))
            ->when($request->filled('status'), fn ($query) => $query->where('status', $request->string('status')))
            ->latest('triggered_at')
            ->paginate(30)
            ->withQueryString();

        return view('admin.alerts.logs', compact('page_title', 'page_description', 'logs', 'clients'));
    }

    public function resolve(AlertLog $alertLog): RedirectResponse
    {
        $alertLog->markResolved();

        return back()->with('success', 'Uyarı çözüldü olarak işaretlendi.');
    }

    private function validated(Request $request): array
    {
        $platforms = implode(',', array_keys(AlertMetricCatalog::all()));
        $metrics = collect(AlertMetricCatalog::all())->flatten()->keys()->implode(',');

        $data = $request->validate([
            'client_id' => ['nullable', 'exists:clients,id'],
            'platform' => ['required', 'in:' . $platforms],
            'name' => ['required', 'string', 'max:255'],
            'metric' => ['required', 'string', 'max:120'],
            'operator' => ['required', 'in:>,>=,<,<=,=,!='],
            'threshold' => ['required', 'numeric'],
            'period' => ['required', 'in:daily,weekly,monthly'],
            'severity' => ['required', 'in:info,warning,critical'],
            'notification_channels' => ['nullable', 'array'],
            'notification_emails' => ['nullable', 'string', 'max:2000'],
            'cooldown_minutes' => ['nullable', 'integer', 'min:0', 'max:10080'],
            'is_active' => ['nullable', 'boolean'],
        ]);

        $data['notification_channels'] = $request->input('notification_channels', []);
        $data['notification_emails'] = $this->normalizeEmails($request->input('notification_emails'));
        $data['cooldown_minutes'] = (int) ($data['cooldown_minutes'] ?? 1440);
        $data['is_active'] = $request->boolean('is_active');

        return $data;
    }

    /**
     * @return array<int, string>
     */
    private function normalizeEmails(?string $value): array
    {
        return collect(preg_split('/\r\n|\r|\n|,|;/', (string) $value) ?: [])
            ->map(fn ($email) => trim((string) $email))
            ->filter(fn ($email) => filter_var($email, FILTER_VALIDATE_EMAIL))
            ->unique()
            ->values()
            ->all();
    }
}
