<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Device;
use Illuminate\Http\Request;

class DeviceController extends Controller
{
    public function index(Request $request)
    {
        return Device::where('tenant_id', $request->user()->tenant_id)->latest()->paginate(25);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'branch_id' => ['nullable', 'integer'],
            'name' => ['required', 'string'],
            'serial_no' => ['required', 'string'],
            'model' => ['required', 'string'],
            'ip_address' => ['nullable', 'ip'],
            'port' => ['nullable', 'integer'],
            'capabilities' => ['array'],
        ]);

        $data['tenant_id'] = $request->user()->tenant_id;
        $data['status'] = 'offline';

        return Device::create($data);
    }

    public function show(Request $request, Device $device)
    {
        abort_unless($device->tenant_id === $request->user()->tenant_id, 404);

        return $device;
    }

    public function update(Request $request, Device $device)
    {
        abort_unless($device->tenant_id === $request->user()->tenant_id, 404);
        $device->update($request->all());

        return $device->fresh();
    }

    public function destroy(Request $request, Device $device)
    {
        abort_unless($device->tenant_id === $request->user()->tenant_id, 404);
        $device->delete();

        return response()->noContent();
    }
}
