<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DeviceController extends Controller
{
    public function index(): JsonResponse
    {
        return response()->json(['data' => DB::table('devices')->where('tenant_id', app('tenant.id'))->get()]);
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'branch_id' => ['required', 'integer'],
            'name' => ['required', 'string', 'max:160'],
            'serial_no' => ['required', 'string', 'max:120'],
            'model' => ['required', 'string', 'max:80'],
            'ip_address' => ['nullable', 'string', 'max:80'],
            'port' => ['nullable', 'integer'],
        ]);

        $id = DB::table('devices')->insertGetId($data + [
            'tenant_id' => app('tenant.id'),
            'status' => 'offline',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return response()->json(['data' => DB::table('devices')->find($id)], 201);
    }

    public function show(int $device): JsonResponse
    {
        return response()->json(['data' => DB::table('devices')->where('tenant_id', app('tenant.id'))->find($device)]);
    }

    public function update(Request $request, int $device): JsonResponse
    {
        DB::table('devices')->where('tenant_id', app('tenant.id'))->where('id', $device)->update($request->all() + ['updated_at' => now()]);

        return $this->show($device);
    }

    public function destroy(int $device): JsonResponse
    {
        DB::table('devices')->where('tenant_id', app('tenant.id'))->where('id', $device)->update(['status' => 'disabled']);

        return response()->json(status: 204);
    }
}
