<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Check if table exists (might be created by Sanctum)
        if (!Schema::hasTable('api_tokens')) {
            Schema::create('api_tokens', function (Blueprint $table) {
                $table->id();
                $table->morphs('tokenable'); // user_id or reseller_id
                $table->string('name'); // Token name (e.g., "Production Server")
                $table->string('token', 64)->unique(); // SHA-256 hash
                $table->json('abilities')->nullable(); // Scopes/permissions
                $table->json('ip_whitelist')->nullable(); // Allowed IPs
                $table->timestamp('last_used_at')->nullable();
                $table->timestamp('expires_at')->nullable();
                $table->boolean('is_active')->default(true);
                $table->timestamps();

                $table->index(['tokenable_type', 'tokenable_id']);
                $table->index('last_used_at');
            });
        } else {
            // Table exists, add missing columns if needed
            Schema::table('api_tokens', function (Blueprint $table) {
                if (!Schema::hasColumn('api_tokens', 'ip_whitelist')) {
                    $table->json('ip_whitelist')->nullable()->after('abilities');
                }
                if (!Schema::hasColumn('api_tokens', 'is_active')) {
                    $table->boolean('is_active')->default(true)->after('expires_at');
                }
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('api_tokens');
    }
};
