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

        $addBatchId = ! Schema::hasColumn('moraqebat_checklists', 'moraqebat_checklist_batch_id');
        $addAbnormalNoise = ! Schema::hasColumn('moraqebat_checklists', 'is_abnormal_noise');
        $addObservedIssue = ! Schema::hasColumn('moraqebat_checklists', 'is_observed_issue');
        $addActionTaken = ! Schema::hasColumn('moraqebat_checklists', 'is_action_taken');

        if (! $addBatchId && ! $addAbnormalNoise && ! $addObservedIssue && ! $addActionTaken) {
            return;
        }

        Schema::table('moraqebat_checklists', function (Blueprint $table) use ($addBatchId, $addAbnormalNoise, $addObservedIssue, $addActionTaken) {
            if ($addBatchId) {
                $table->foreignId('moraqebat_checklist_batch_id')
                    ->nullable()
                    ->after('id')
                    ->constrained('moraqebat_checklist_batches')
                    ->nullOnDelete();
            }

            if ($addAbnormalNoise) {
                $table->boolean('is_abnormal_noise')->default(false)->after('is_cleanliness_checked');
            }

            if ($addObservedIssue) {
                $table->boolean('is_observed_issue')->default(false)->after('is_abnormal_noise');
            }

            if ($addActionTaken) {
                $table->boolean('is_action_taken')->default(false)->after('is_observed_issue');
            }
        });
    }

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

        Schema::table('moraqebat_checklists', function (Blueprint $table) {
            if (Schema::hasColumn('moraqebat_checklists', 'moraqebat_checklist_batch_id')) {
                $table->dropConstrainedForeignId('moraqebat_checklist_batch_id');
            }

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

            if ($columns !== []) {
                $table->dropColumn($columns);
            }
        });
    }
};
