<?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
    {
        Schema::create('threecx_tokens', function (Blueprint $table) {
            $table->id();
            $table->unsignedInteger('user_id')->nullable();
            $table->string('instance_id')->index(); // 3CX instance/tenant ID
            $table->string('instance_name')->nullable();
            $table->string('instance_url')->nullable();
            $table->text('access_token');
            $table->text('refresh_token');
            $table->timestamp('expires_at')->nullable();
            $table->timestamp('connected_at')->nullable();
            $table->json('scopes')->nullable(); // Store granted scopes
            $table->timestamps();
            $table->softDeletes();
            
            // Indexes
            $table->index(['user_id', 'instance_id']);
            $table->index('expires_at');
            $table->index('connected_at');
            
            // Foreign key constraint (nullable for system tokens)
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            
            // Unique constraint to prevent duplicate connections
            $table->unique(['user_id', 'instance_id'], 'unique_user_instance');
        });
    }

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