<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Alert;
use App\Models\AlertRule;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class RasAlertsController extends Controller
{
    public function index(): JsonResponse
    {
        $userId = Auth::id();
        $alerts = Alert::query()
            ->where('user_id', $userId)
            ->orderByDesc('created_at')
            ->limit(20)
            ->get();

        return $this->success($alerts);
    }

    public function alerts(): JsonResponse
    {
        $userId = Auth::id();
        $alerts = Alert::query()
            ->where('user_id', $userId)
            ->orderByDesc('created_at')
            ->get();

        return $this->success($alerts);
    }

    public function upsertAlerts(Request $request): JsonResponse
    {
        $userId = Auth::id();
        $data = $request->validate([
            'items' => ['required', 'array'],
            'items.*.id' => ['required', 'string', 'max:80'],
            'items.*.created_at' => ['required', 'date'],
            'items.*.event_date' => ['required', 'date_format:Y-m-d'],
            'items.*.severity' => ['required', 'in:INFO,WARN,CRIT'],
            'items.*.status' => ['required', 'in:NEW,ACK,RESOLVED,MUTED'],
            'items.*.source' => ['required', 'string', 'max:50'],
            'items.*.type' => ['required', 'string', 'max:80'],
            'items.*.title' => ['required', 'string', 'max:255'],
            'items.*.message' => ['nullable', 'string'],
            'items.*.entity' => ['nullable', 'array'],
            'items.*.actions' => ['nullable', 'array'],
            'items.*.meta' => ['nullable', 'array'],
            'items.*.notes' => ['nullable', 'array'],
            'items.*.mute_until' => ['nullable', 'date'],
        ]);

        $items = $data['items'] ?? [];
        foreach ($items as $a) {
            Alert::updateOrCreate(
                ['user_id' => $userId, 'external_id' => (string) $a['id']],
                [
                    'dedupe_key' => $a['dedupe_key'] ?? null,
                    'source' => (string) ($a['source'] ?? ''),
                    'type' => (string) ($a['type'] ?? ''),
                    'severity' => (string) ($a['severity'] ?? 'WARN'),
                    'status' => (string) ($a['status'] ?? 'NEW'),
                    'title' => (string) ($a['title'] ?? ''),
                    'message' => $a['message'] ?? null,
                    'event_date' => (string) ($a['event_date'] ?? null),
                    'entity' => $a['entity'] ?? null,
                    'actions' => $a['actions'] ?? null,
                    'meta' => $a['meta'] ?? null,
                    'notes' => $a['notes'] ?? null,
                    'mute_until' => $a['mute_until'] ?? null,
                    'created_at' => $a['created_at'] ?? now(),
                ]
            );
        }

        $alerts = Alert::query()
            ->where('user_id', $userId)
            ->orderByDesc('created_at')
            ->get();

        return $this->success($alerts, 'Alerts saved');
    }

    public function rules(): JsonResponse
    {
        $userId = Auth::id();
        $rules = AlertRule::query()
            ->where('user_id', $userId)
            ->orderByDesc('updated_at')
            ->get();

        return $this->success($rules);
    }

    public function upsertRules(Request $request): JsonResponse
    {
        $userId = Auth::id();
        $data = $request->validate([
            'items' => ['required', 'array'],
            'items.*.id' => ['required', 'string', 'max:80'],
            'items.*.type' => ['required', 'string', 'max:80'],
            'items.*.is_enabled' => ['required', 'boolean'],
            'items.*.severity_default' => ['required', 'in:INFO,WARN,CRIT'],
            'items.*.thresholds' => ['nullable', 'array'],
        ]);

        $items = $data['items'] ?? [];
        foreach ($items as $r) {
            AlertRule::updateOrCreate(
                ['user_id' => $userId, 'external_id' => (string) $r['id']],
                [
                    'type' => (string) ($r['type'] ?? ''),
                    'is_enabled' => (bool) ($r['is_enabled'] ?? true),
                    'severity_default' => (string) ($r['severity_default'] ?? 'WARN'),
                    'thresholds' => $r['thresholds'] ?? null,
                ]
            );
        }

        $rules = AlertRule::query()
            ->where('user_id', $userId)
            ->orderByDesc('updated_at')
            ->get();

        return $this->success($rules, 'Rules saved');
    }
}
