<?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
    {
        if (! Schema::hasTable('purchase_items')) {
            Schema::create('purchase_items', function (Blueprint $table) {
                $table->id();
                $table->foreignId('purchase_id')->constrained('purchases')->cascadeOnDelete();
                $table->foreignId('item_id')->constrained('items')->cascadeOnDelete();
                $table->string('item_name');
                $table->string('variation_type')->nullable();
                $table->unsignedInteger('quantity');
                $table->decimal('purchase_price', 24, 8);
                $table->decimal('total_amount', 24, 8);
                $table->integer('stock_before')->default(0);
                $table->integer('stock_after')->default(0);
                $table->integer('variation_stock_before')->nullable();
                $table->integer('variation_stock_after')->nullable();
                $table->timestamps();

                $table->index(['item_id', 'created_at']);
            });
        }
    }

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