<?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('sales_orders', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->string('status', 40);
            $table->uuid('correlation_id')->nullable();
            $table->timestamps();

            $table->index(['tenant_id', 'status'], 'sales_orders_tenant_status');
        });

        Schema::create('sales_order_lines', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('sales_order_id')->constrained('sales_orders')->cascadeOnDelete();
            $table->unsignedSmallInteger('line_position');
            $table->foreignId('warehouse_id')->constrained('inventory_warehouses')->restrictOnDelete();
            $table->foreignId('item_id')->constrained('inventory_items')->restrictOnDelete();
            $table->decimal('quantity_ordered', 24, 8);
            $table->decimal('quantity_reserved', 24, 8)->default(0);
            $table->decimal('quantity_fulfilled', 24, 8)->default(0);
            $table->uuid('reservation_public_id')->nullable();
            $table->timestamps();

            $table->index(['tenant_id', 'sales_order_id'], 'sales_order_lines_tenant_order');
        });
    }

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