<?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::table('bio_racks', function (Blueprint $table) {
            if (!Schema::hasColumn('bio_racks', 'slot_count')) {
                $table->integer('slot_count')->default(1)->after('name');
            }
        });

        DB::table('bio_racks')
            ->where(function ($query) {
                $query->whereNull('slot_count')
                    ->orWhere('slot_count', '<=', 1);
            })
            ->orderBy('id')
            ->get(['id', 'level'])
            ->each(function ($rack) {
                DB::table('bio_racks')
                    ->where('id', $rack->id)
                    ->update(['slot_count' => max((int) ($rack->level ?? 1), 1)]);
            });
    }

    public function down(): void
    {
        Schema::table('bio_racks', function (Blueprint $table) {
            if (Schema::hasColumn('bio_racks', 'slot_count')) {
                $table->dropColumn('slot_count');
            }
        });
    }
};
