<?php

namespace App\Http\Controllers\System;

use App\Http\Controllers\Controller;
use App\Models\Stats\StatAlert;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;

class SystemAlertController extends Controller
{
    /**
     * 시스템 알림 목록
     */
    public function index(Request $request): View
    {
        $query = StatAlert::query()->orderByDesc('created_at');

        // 도메인 필터
        if ($request->filled('domain')) {
            $query->where('domain', $request->domain);
        }

        // 심각도 필터
        if ($request->filled('severity')) {
            $query->where('severity', $request->severity);
        }

        // 상태 필터
        if ($request->filled('status')) {
            match ($request->status) {
                'unread' => $query->where('is_read', false),
                'unresolved' => $query->where('is_resolved', false),
                default => null,
            };
        }

        // 날짜 범위 필터
        if ($request->filled('date_from')) {
            $query->where('created_at', '>=', $request->date_from.' 00:00:00');
        }
        if ($request->filled('date_to')) {
            $query->where('created_at', '<=', $request->date_to.' 23:59:59');
        }

        $alerts = $query->paginate(50)->withQueryString();

        // 통계
        $stats = [
            'total' => StatAlert::count(),
            'unread' => StatAlert::where('is_read', false)->count(),
            'unresolved' => StatAlert::where('is_resolved', false)->count(),
            'critical' => StatAlert::where('severity', 'critical')->where('is_resolved', false)->count(),
        ];

        // 도메인 목록 (필터용)
        $domains = StatAlert::select('domain')->distinct()->pluck('domain');

        return view('system.alerts.index', compact('alerts', 'stats', 'domains'));
    }

    /**
     * 읽음 처리
     */
    public function markAsRead(int $id): Response
    {
        $alert = StatAlert::findOrFail($id);
        $alert->update(['is_read' => true]);

        return response('', 200, ['HX-Refresh' => 'true']);
    }

    /**
     * 해결 처리
     */
    public function resolve(int $id): Response
    {
        $alert = StatAlert::findOrFail($id);
        $alert->update([
            'is_read' => true,
            'is_resolved' => true,
            'resolved_at' => now(),
        ]);

        return response('', 200, ['HX-Refresh' => 'true']);
    }

    /**
     * 전체 읽음 처리
     */
    public function markAllAsRead(): Response
    {
        StatAlert::where('is_read', false)->update(['is_read' => true]);

        return response('', 200, ['HX-Refresh' => 'true']);
    }
}
