<?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('product_batches', function (Blueprint $table) {
            $table->id();
            $table->foreignId('product_id')->constrained('products')->cascadeOnDelete();
            $table->foreignId('supplier_id')->nullable()->constrained('suppliers')->nullOnDelete();
            $table->foreignId('purchase_id')->nullable()->constrained('purchases')->nullOnDelete();
            
            // Batch Information
            $table->string('batch_number')->nullable()->index();
            $table->string('lot_number')->nullable()->index();
            $table->string('serial_number')->nullable()->unique()->index();
            
            // Expiry Management
            $table->date('manufacture_date')->nullable();
            $table->date('expiry_date')->nullable()->index();
            
            // Stock Information
            $table->integer('initial_quantity')->default(0);
            $table->integer('current_quantity')->default(0);
            $table->integer('reserved_quantity')->default(0);
            
            // Pricing
            $table->decimal('batch_cost_price', 12, 2)->nullable();
            $table->decimal('batch_sale_price', 12, 2)->nullable();
            
            // Location Tracking
            $table->string('warehouse_location')->nullable();
            
            // Quality Control
            $table->string('quality_status')->default('approved')->index();
            $table->text('quality_notes')->nullable();
            
            // Additional Information
            $table->text('notes')->nullable();
            
            // Audit
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            
            $table->timestamps();
            $table->softDeletes();
            
            // Indexes
            $table->index(['product_id', 'expiry_date']);
            $table->index(['product_id', 'current_quantity']);
            $table->index(['expiry_date', 'current_quantity']);
        });
    }

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