<?php

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

class CreateShipmentItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('shipment_items', function (Blueprint $table) {
            $table->bigIncrements('id');

            // Link to shipments
            $table->foreignId('shipment_id')->constrained('shipments')->onDelete('cascade');

            // Link to orders. assuming orders.id is bigIncrements
            $table->foreignId('order_id')->constrained('orders')->onDelete('restrict');

            // Snapshots (optional) — store basic order totals at time of assignment
            $table->integer('order_ctn')->nullable()->default(0);
            $table->integer('order_qty')->nullable()->default(0);
            $table->integer('order_ttl_qty')->nullable()->default(0);
            $table->decimal('order_ttl_amount', 16, 2)->nullable()->default(0.00);
            $table->decimal('order_ttl_kg', 14, 3)->nullable()->default(0.000);

            $table->timestamps();

            // Prevent duplicate assignment of same order to the same shipment
            $table->unique(['shipment_id', 'order_id']);

            // We will check order_id uniqueness across shipments in app logic (see below)
            $table->index('order_id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('shipment_items');
    }
}
