<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('division_deliveries', function (Blueprint $table) {
            $table->id();
            $table->foreignId('division_id')->constrained('departments')->onDelete('restrict');
            $table->foreignId('item_id')->constrained('items')->onDelete('restrict');
            $table->decimal('total_quantity_delivered', 15, 2)->default(0);
            $table->decimal('current_available_quantity', 15, 2)->default(0);
            $table->decimal('total_quantity_issued', 15, 2)->default(0);
            $table->decimal('average_unit_price', 10, 2)->default(0);
            $table->decimal('total_value', 15, 2)->default(0);
            $table->date('first_delivery_date')->nullable();
            $table->date('last_delivery_date')->nullable();
            $table->timestamp('last_updated')->nullable();
            $table->timestamps();

            // Unique constraint: one record per division-item combination
            $table->unique(['division_id', 'item_id']);

            // Indexes for performance
            $table->index(['division_id']);
            $table->index(['item_id']);
            $table->index(['total_quantity_delivered']);
            $table->index(['current_available_quantity']);
        });
    }

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