<?php

namespace Modules\SmartStorage\Http\Controllers;

use Illuminate\Routing\Controller;
use Modules\SmartStorage\Entities\SsDevice;

class DeviceController extends Controller
{
    protected function authorizeManage(): void
    {
        if (!auth()->user()->can('smart_storage.manage')) {
            abort(403, 'Unauthorized action.');
        }
    }

    public function index()
    {
        $this->authorizeManage();

        $devices = SsDevice::orderByDesc('last_seen_at')->get();

        return view('smartstorage::devices.index', compact('devices'));
    }

    public function approve($id)
    {
        $this->authorizeManage();

        $device = SsDevice::findOrFail($id);
        $device->approved = true;
        $device->save();

        return back()->with('status', ['success' => 1, 'msg' => 'Device approved.']);
    }

    public function revoke($id)
    {
        $this->authorizeManage();

        $device = SsDevice::findOrFail($id);
        $device->approved = false;
        $device->save();

        return back()->with('status', ['success' => 1, 'msg' => 'Device access revoked.']);
    }

    public function destroy($id)
    {
        $this->authorizeManage();

        SsDevice::where('id', $id)->delete();

        return back()->with('status', ['success' => 1, 'msg' => 'Device removed.']);
    }
}
