<?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
    {
        Schema::create('sale_items', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('sale_id')->constrained()->cascadeOnDelete();
            $table->foreignId('factory_product_id')->constrained()->cascadeOnDelete();
            $table->foreignId('customer_order_item_id')->nullable()->constrained()->nullOnDelete();
            $table->decimal('quantity', 12, 3);
            $table->decimal('total_weight', 12, 3);
            $table->decimal('weight_price', 12, 2);
            $table->date('expiry_date');
            $table->timestamps();
        });

        Schema::table('sale_packs', function (Blueprint $table): void {
            $table->foreignId('sale_item_id')->nullable()->after('sale_id')->constrained()->nullOnDelete();
        });
    }

    public function down(): void
    {
        Schema::table('sale_packs', function (Blueprint $table): void {
            $table->dropConstrainedForeignId('sale_item_id');
        });

        Schema::dropIfExists('sale_items');
    }
};
