<?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('purchase_orders', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->string('po_number', 64);
            $table->string('status', 32)->default('open');
            $table->timestamps();

            $table->unique(['tenant_id', 'po_number'], 'po_tenant_num_uq');
            $table->index(['tenant_id', 'id'], 'po_tenant_seq');
        });

        Schema::create('purchase_order_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('purchase_order_id', 'poi_po_fk')->constrained('purchase_orders')->cascadeOnDelete();
            $table->foreignId('inventory_item_id', 'poi_item_fk')->constrained('inventory_items')->restrictOnDelete();
            $table->decimal('quantity_ordered', 18, 4)->default(0);
            $table->timestamps();
            $table->softDeletes();

            $table->index(['tenant_id', 'purchase_order_id', 'id'], 'poi_tenant_po_seq');
        });

        Schema::create('goods_receipts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('purchase_order_id', 'gr_po_fk')->constrained('purchase_orders')->restrictOnDelete();
            $table->string('status', 32)->default('pending');
            $table->timestamps();

            $table->index(['tenant_id', 'purchase_order_id', 'id'], 'gr_tenant_po_seq');
        });

        Schema::create('goods_receipt_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('goods_receipt_id', 'gri_gr_fk')->constrained('goods_receipts')->cascadeOnDelete();
            $table->foreignId('purchase_order_item_id', 'gri_poi_fk')->constrained('purchase_order_items')->restrictOnDelete();
            $table->decimal('quantity_received', 18, 4)->default(0);
            $table->timestamp('quarantined_at')->nullable();
            $table->string('integrity_violation_code', 64)->nullable();
            $table->timestamps();

            $table->index(['tenant_id', 'goods_receipt_id', 'id'], 'gri_tenant_gr_seq');
            $table->index(['tenant_id', 'quarantined_at'], 'gri_quarantine');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('goods_receipt_items');
        Schema::dropIfExists('goods_receipts');
        Schema::dropIfExists('purchase_order_items');
        Schema::dropIfExists('purchase_orders');
    }
};
