<?php

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

class CreateOauthTokensTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('oauth_tokens', function (Blueprint $table) {
            $table->id();
            
            // Integration identification
            $table->string('provider')->index(); // 'xero', 'twilio', 'google', 'microsoft', etc.
            $table->string('provider_type')->default('oauth2'); // 'oauth2', 'oauth1', 'api_key', 'basic_auth'
            
            // Scope - system-wide, user-specific, or tenant-specific
            $table->string('scope')->default('system'); // 'system', 'user', 'tenant'
            $table->unsignedInteger('user_id')->nullable(); // For user-specific tokens
            $table->string('tenant_id')->nullable(); // For multi-tenant providers (Xero orgs, etc.)
            
            // OAuth2 Standard Fields
            $table->text('access_token');
            $table->text('refresh_token')->nullable();
            $table->timestamp('expires_at')->nullable();
            $table->json('scopes')->nullable(); // Array of granted scopes
            
            // Provider-specific data
            $table->json('provider_data')->nullable(); // Flexible field for provider-specific info
            
            // Metadata
            $table->string('token_type')->default('Bearer');
            $table->string('status')->default('active'); // 'active', 'expired', 'revoked', 'suspended'
            $table->timestamp('connected_at')->nullable();
            $table->timestamp('last_used_at')->nullable();
            $table->timestamps();
            $table->softDeletes();
            
            // Indexes for performance
            $table->index(['provider', 'scope']);
            $table->index(['provider', 'user_id']);
            $table->index(['provider', 'tenant_id']);
            $table->index(['status', 'expires_at']);
            $table->index('last_used_at');
            
            // Constraints
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            
            // Unique constraints to prevent duplicates
            $table->unique(['provider', 'scope', 'user_id', 'tenant_id'], 'unique_provider_token');
        });
    }

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