<?php

namespace App\Http\Controllers\Api;

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

class DeviceController extends Controller
{
    /**
     * Register a device and return a token.
     */
    public function register(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
        ]);

        $token = Str::random(40);

        $id = DB::table('devices')->insertGetId([
            'name' => $data['name'],
            'token' => $token,
            'status' => 'active',
            'last_seen_at' => now(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return response()->json([
            'token' => $token,
            'device' => [
                'id' => $id,
                'name' => $data['name'],
                'status' => 'active',
            ],
        ]);
    }
}
