<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
    public function up(): void
    {
        if (!Schema::hasTable('devices')) {
            Schema::create('devices', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('name', 150)->nullable();
                // store hashed token (sha256 hex = 64 chars)
                $table->string('api_token', 64)->unique();
                $table->timestamp('last_seen_at')->nullable();
                $table->timestamps();
            });
        } else {
            // Ensure required columns exist (for older installs)
            if (!Schema::hasColumn('devices', 'api_token')) {
                Schema::table('devices', function (Blueprint $table) {
                    $table->string('api_token', 64)->unique()->after('name');
                });
            }
            if (!Schema::hasColumn('devices', 'last_seen_at')) {
                Schema::table('devices', function (Blueprint $table) {
                    $table->timestamp('last_seen_at')->nullable()->after('api_token');
                });
            }
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('devices');
    }
};
