<?php

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

return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('moraqebat_checklists')) {
            return;
        }

        $addScore = ! Schema::hasColumn('moraqebat_checklists', 'condition_score');
        $addTrend = ! Schema::hasColumn('moraqebat_checklists', 'condition_trend');

        if (! $addScore && ! $addTrend) {
            return;
        }

        Schema::table('moraqebat_checklists', function (Blueprint $table) use ($addScore, $addTrend) {
            if ($addScore) {
                $table->smallInteger('condition_score')->default(0);
            }

            if ($addTrend) {
                $table->string('condition_trend', 16)->nullable();
            }
        });
    }

    public function down(): void
    {
        if (! Schema::hasTable('moraqebat_checklists')) {
            return;
        }

        $columns = collect(['condition_score', 'condition_trend'])
            ->filter(fn (string $column): bool => Schema::hasColumn('moraqebat_checklists', $column))
            ->values()
            ->all();

        if ($columns === []) {
            return;
        }

        Schema::table('moraqebat_checklists', function (Blueprint $table) use ($columns) {
            $table->dropColumn($columns);
        });
    }
};
