<?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('production_order_materials')) {
            Schema::create('production_order_materials', function (Blueprint $table) {
                $table->id();
                $table->foreignId('production_order_id')
                    ->constrained('production_orders')
                    ->cascadeOnDelete();
                $table->foreignId('purchase_product_id')
                    ->constrained('purchase_products')
                    ->restrictOnDelete();
                $table->decimal('quantity', 15, 3);
                $table->timestamps();

                $table->unique(
                    ['production_order_id', 'purchase_product_id'],
                    'production_order_materials_order_product_unique',
                );
            });

            return;
        }

        if (! Schema::hasIndex(
            'production_order_materials',
            'production_order_materials_order_product_unique',
        )) {
            Schema::table('production_order_materials', function (Blueprint $table) {
                $table->unique(
                    ['production_order_id', 'purchase_product_id'],
                    'production_order_materials_order_product_unique',
                );
            });
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('production_order_materials');
    }
};
