<?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
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('tenants', function (Blueprint $table) {
            $table->string('tenant_id')->nullable()->after('name');
            $table->string('domain')->nullable()->after('tenant_id');
            $table->string('app_client_id')->nullable()->after('domain');
            $table->text('app_client_secret')->nullable()->after('app_client_id');
            $table->string('app_certificate_thumbprint')->nullable()->after('app_client_secret');
            $table->string('app_status')->default('unknown')->after('app_certificate_thumbprint');
            $table->text('app_notes')->nullable()->after('app_status');

            $table->unique('tenant_id');
        });

        Schema::table('tenants', function (Blueprint $table) {
            $table->index('domain');
            $table->index('app_status');
        });

        DB::table('tenants')
            ->whereNull('tenant_id')
            ->update(['tenant_id' => DB::raw('external_id')]);
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('tenants', function (Blueprint $table) {
            $table->dropUnique(['tenant_id']);
            $table->dropColumn([
                'tenant_id',
                'domain',
                'app_client_id',
                'app_client_secret',
                'app_certificate_thumbprint',
                'app_status',
                'app_notes',
            ]);
        });
    }
};
