<?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->boolean('is_current')->default(false)->after('status');
        });

        DB::table('tenants')->update(['is_current' => false]);

        $preferredCurrentId = DB::table('tenants')
            ->whereNull('deleted_at')
            ->where('status', 'active')
            ->where('app_status', 'ok')
            ->orderBy('created_at')
            ->value('id');

        if ($preferredCurrentId === null) {
            $preferredCurrentId = DB::table('tenants')
                ->whereNull('deleted_at')
                ->where('status', 'active')
                ->where('tenant_id', '<>', 'local-tenant')
                ->orderBy('created_at')
                ->value('id');
        }

        if ($preferredCurrentId === null) {
            $preferredCurrentId = DB::table('tenants')
                ->whereNull('deleted_at')
                ->where('status', 'active')
                ->orderBy('created_at')
                ->value('id');
        }

        if ($preferredCurrentId !== null) {
            DB::table('tenants')
                ->where('id', $preferredCurrentId)
                ->update(['is_current' => true]);
        }

        DB::table('tenants')
            ->where('tenant_id', 'local-tenant')
            ->update(['status' => 'archived', 'is_current' => false]);

        DB::statement('CREATE UNIQUE INDEX tenants_current_unique ON tenants (is_current) WHERE is_current = true AND deleted_at IS NULL');
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        DB::statement('DROP INDEX IF EXISTS tenants_current_unique');

        Schema::table('tenants', function (Blueprint $table) {
            $table->dropColumn('is_current');
        });
    }
};
