<?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
    {
        if (!Schema::hasTable('departments')) {
            return;
        }

        if (!Schema::hasColumn('departments', 'code')) {
            Schema::table('departments', function (Blueprint $table) {
                $table->string('code')->nullable()->after('name');
            });
        }

        DB::table('departments')
            ->whereNull('code')
            ->orWhere('code', '')
            ->update(['code' => DB::raw('slug')]);

        if (!$this->indexExists('departments', 'departments_dealer_id_code_unique')) {
            Schema::table('departments', function (Blueprint $table) {
                $table->unique(['dealer_id', 'code']);
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        if (!Schema::hasTable('departments')) {
            return;
        }

        if ($this->indexExists('departments', 'departments_dealer_id_code_unique')) {
            Schema::table('departments', function (Blueprint $table) {
                $table->dropUnique('departments_dealer_id_code_unique');
            });
        }

        if (Schema::hasColumn('departments', 'code')) {
            Schema::table('departments', function (Blueprint $table) {
                $table->dropColumn('code');
            });
        }
    }

    private function indexExists(string $table, string $indexName): bool
    {
        return DB::table('information_schema.statistics')
            ->where('table_schema', DB::getDatabaseName())
            ->where('table_name', $table)
            ->where('index_name', $indexName)
            ->exists();
    }
};
