<?php

namespace Modules\LabCore\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\LabCore\Entities\LabAgent;
use Modules\LabCore\Entities\LabDevice;
use Modules\LabCore\Entities\Services\DriverRegistry;

class LabDeviceController extends Controller
{
    private function authorizeLab(): void
    {
        if (!auth()->user()->can('lab.manage_devices')) {
            abort(403, 'Unauthorized action.');
        }
    }

    public function index()
    {
        $this->authorizeLab();
        $businessId = request()->session()->get('user.business_id');

        $devices = LabDevice::with('agent')
            ->where('business_id', $businessId)
            ->latest('id')
            ->get();

        $agents  = LabAgent::where('business_id', $businessId)->orderBy('name')->get();
        $vendors = DriverRegistry::all();

        return view('labCore::devices.index', compact('devices', 'agents', 'vendors'));
    }

    public function store(Request $request)
    {
        $this->authorizeLab();
        $data = $this->validateDevice($request);
        $data['business_id'] = $request->session()->get('user.business_id');

        LabDevice::create($data);

        return redirect()->route('lab.devices.index')->with('status', [
            'success' => 1, 'msg' => 'Device added.',
        ]);
    }

    public function update(Request $request, $id)
    {
        $this->authorizeLab();
        $device = LabDevice::findOrFail($id);
        $device->update($this->validateDevice($request));

        return redirect()->route('lab.devices.index')->with('status', [
            'success' => 1, 'msg' => 'Device updated.',
        ]);
    }

    public function destroy($id)
    {
        $this->authorizeLab();
        LabDevice::findOrFail($id)->delete();

        return redirect()->route('lab.devices.index')->with('status', [
            'success' => 1, 'msg' => 'Device deleted.',
        ]);
    }

    private function validateDevice(Request $request): array
    {
        return $request->validate([
            'agent_id'        => 'nullable|integer|exists:lab_agents,id',
            'vendor'          => 'required|string|max:30',
            'model'           => 'nullable|string|max:60',
            'name'            => 'required|string|max:120',
            'connection_type' => 'required|in:tcp,serial,serial2eth',
            'comm_protocol'   => 'nullable|string|max:40',
            'host'            => 'nullable|string|max:45',
            'port'            => 'nullable|integer|min:1|max:65535',
            'com_port'        => 'nullable|string|max:20',
            'baud'            => 'nullable|integer',
            'status'          => 'required|in:online,offline,disabled',
        ]);
    }
}
