<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('provider_connections', function (Blueprint $table) {
            $table->id();
            $table->foreignId('managed_environment_id')->constrained()->cascadeOnDelete();
            $table->string('provider');
            $table->string('entra_tenant_id');
            $table->string('display_name');
            $table->boolean('is_default')->default(false);
            $table->string('status')->default('needs_consent');
            $table->string('health_status')->default('unknown');
            $table->jsonb('scopes_granted')->default('{}');
            $table->timestamp('last_health_check_at')->nullable();
            $table->string('last_error_reason_code')->nullable();
            $table->string('last_error_message')->nullable();
            $table->jsonb('metadata')->default('{}');
            $table->timestamps();

            $table->unique(['managed_environment_id', 'provider', 'entra_tenant_id']);

            $table->index(['managed_environment_id', 'provider', 'status']);
            $table->index(['managed_environment_id', 'provider', 'health_status']);
        });

        DB::statement('CREATE UNIQUE INDEX provider_connections_default_unique ON provider_connections (managed_environment_id, provider) WHERE is_default = true');
    }

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