<?php

namespace App\Http\Controllers;

use App\Models\OltDevice;
use App\Services\OltSshService;
use Illuminate\Http\Request;

class OnuSearchController extends Controller
{
    public function index()
    {
        $devices = OltDevice::where('active', true)->get();
        return view('onu-search.index', compact('devices'));
    }

    public function search(Request $request, OltDevice $device)
    {
        $request->validate([
            'serial_number' => 'required|string|min:4|max:20',
        ]);

        set_time_limit(300);

        try {
            $ssh = new OltSshService($device);
            if (!$ssh->connectLong()) {
                return response()->json(['success' => false, 'message' => 'No se pudo conectar a la OLT.']);
            }

            $result = $ssh->findOnuBySerialNumber($request->serial_number);

            $ssh->logActivity(
                'search_onu',
                'SN:' . strtoupper(trim($request->serial_number)),
                'show gpon onu baseinfo (scan)',
                $result ? "Found at gpon-olt_{$result['frame']}/{$result['slot']}/{$result['port']}:{$result['onu_id']}" : 'Not found',
                $result !== null
            );

            $ssh->disconnect();

            if ($result === null) {
                return response()->json([
                    'success' => true,
                    'found'   => false,
                    'message' => 'ONU no encontrada en ningún puerto de esta OLT.',
                ]);
            }

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