<?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('material_components')) {
            Schema::create('material_components', function (Blueprint $table) {
                $table->id();
                $table->foreignId('material_id')->constrained('materials')->cascadeOnDelete();
                $table->foreignId('component_material_id')->constrained('materials')->cascadeOnDelete();
                $table->decimal('qty', 15, 4)->default(1);
                $table->timestamps();
            });

            return;
        }

        Schema::table('material_components', function (Blueprint $table) {
            if (!Schema::hasColumn('material_components', 'material_id')) {
                $table->foreignId('material_id')->nullable()->after('id');
            }

            if (!Schema::hasColumn('material_components', 'component_material_id')) {
                $table->foreignId('component_material_id')->nullable()->after('material_id');
            }

            if (!Schema::hasColumn('material_components', 'qty')) {
                $table->decimal('qty', 15, 4)->default(1)->after('component_material_id');
            }

            if (!Schema::hasColumn('material_components', 'created_at')) {
                $table->timestamp('created_at')->nullable();
            }

            if (!Schema::hasColumn('material_components', 'updated_at')) {
                $table->timestamp('updated_at')->nullable();
            }
        });
    }

    public function down(): void
    {
        if (Schema::hasTable('material_components')) {
            Schema::dropIfExists('material_components');
        }
    }
};