<?php

namespace Modules\LabCore\Http\Controllers;

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

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

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

        $agents = LabAgent::withCount('devices')
            ->where('business_id', $businessId)
            ->latest('id')
            ->get();

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

    public function store(Request $request)
    {
        $this->authorizeLab();
        $data = $request->validate([
            'name' => 'required|string|max:120',
            'code' => 'required|string|max:60|alpha_dash|unique:lab_agents,code',
        ]);

        $agent = LabAgent::create([
            'business_id' => $request->session()->get('user.business_id'),
            'name'        => $data['name'],
            'code'        => $data['code'],
            'api_token'   => LabAgent::freshToken(),
            'status'      => 'active',
        ]);

        return redirect()->route('lab.agents.index')->with('status', [
            'success' => 1,
            'msg'     => "Agent '{$agent->name}' created. API token: {$agent->api_token}",
        ]);
    }

    public function regenerateToken($id)
    {
        $this->authorizeLab();
        $agent = LabAgent::findOrFail($id);
        $agent->update(['api_token' => LabAgent::freshToken()]);

        return redirect()->route('lab.agents.index')->with('status', [
            'success' => 1,
            'msg'     => "New API token for '{$agent->name}': {$agent->api_token}",
        ]);
    }

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

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