<?php

namespace App\Http\Controllers;

use App\Models\AlertSetting;
use App\Models\OltDevice;
use App\Models\PowerAlert;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;

class PowerAlertController extends Controller
{
    public function index(Request $request)
    {
        $devices = OltDevice::where('active', true)->get();

        $query = PowerAlert::with('device')->latest();

        if ($request->filled('device')) {
            $query->where('olt_device_id', $request->device);
        }
        if ($request->filled('severity')) {
            $query->where('severity', $request->severity);
        }
        if ($request->input('status') === 'unacknowledged') {
            $query->unacknowledged();
        } elseif ($request->input('status') === 'acknowledged') {
            $query->where('acknowledged', true);
        }

        $alerts = $query->paginate(50)->withQueryString();
        $unacknowledgedCount = PowerAlert::unacknowledged()->count();

        return view('power-alerts.index', compact('devices', 'alerts', 'unacknowledgedCount'));
    }

    public function settings()
    {
        $devices = OltDevice::where('active', true)->get();
        $settings = AlertSetting::all()->keyBy('olt_device_id');

        // Global/default settings
        $global = AlertSetting::getForDevice(null);

        return response()->json([
            'success'  => true,
            'global'   => $global,
            'devices'  => $devices,
            'settings' => $settings,
        ]);
    }

    public function updateSettings(Request $request)
    {
        $request->validate([
            'device_id'          => 'nullable|integer|exists:olt_devices,id',
            'warning_threshold'  => 'required|numeric|min:-40|max:0',
            'critical_threshold' => 'required|numeric|min:-40|max:0',
            'email_enabled'      => 'boolean',
            'email_recipients'   => 'nullable|string|max:500',
            'active'             => 'boolean',
        ]);

        $setting = AlertSetting::updateOrCreate(
            ['olt_device_id' => $request->device_id],
            [
                'warning_threshold'  => $request->warning_threshold,
                'critical_threshold' => $request->critical_threshold,
                'email_enabled'      => $request->boolean('email_enabled'),
                'email_recipients'   => $request->email_recipients,
                'active'             => $request->boolean('active', true),
            ]
        );

        return response()->json(['success' => true, 'setting' => $setting]);
    }

    public function acknowledge(PowerAlert $alert)
    {
        $alert->update(['acknowledged' => true]);
        return response()->json(['success' => true]);
    }

    public function acknowledgeAll(Request $request)
    {
        $query = PowerAlert::unacknowledged();
        if ($request->filled('device')) {
            $query->where('olt_device_id', $request->device);
        }
        $count = $query->update(['acknowledged' => true]);

        return response()->json(['success' => true, 'count' => $count]);
    }

    public function scan(Request $request)
    {
        set_time_limit(600);

        $deviceOption = $request->filled('device') ? ['--device' => $request->device] : [];

        try {
            Artisan::call('olt:check-power', $deviceOption);
            $output = Artisan::output();

            return response()->json([
                'success' => true,
                'message' => 'Escaneo completado.',
                'output'  => trim($output),
            ]);
        } catch (\Throwable $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error: ' . $e->getMessage(),
            ]);
        }
    }
}
