<?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('acc_stocks', function (Blueprint $table) {
            // Keep engine/collation consistent
            $table->engine    = 'InnoDB';
            $table->charset   = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';

            $table->id(); // BIGINT UNSIGNED

            // FK columns only (constraints added in next migration)
            $table->unsignedBigInteger('company_id');           // -> companies.id (required)
            $table->unsignedBigInteger('branch_id')->nullable();   // -> branches.id
            $table->unsignedBigInteger('warehouse_id')->nullable(); // -> warehouses.id
            $table->unsignedBigInteger('product_id');              // -> products/finish_products/raw_materials.id (required)

            $table->date('date'); // NOT NULL

            // Polymorphic (required)
            $table->string('stockable_type', 191);
            $table->unsignedBigInteger('stockable_id');

            // Enum: In / Out
            $table->enum('stock_type', ['In', 'Out']);

            // Pricing/qty (NOT NULL, no default per your dump)
            $table->decimal('price', 15, 2);
            $table->double('quantity');
            // amount VIRTUAL GENERATED (nullable in your dump)
            $table->decimal('amount', 15, 2)->nullable()->virtualAs('quantity * price');

            $table->double('actual_qty');

            // Audit
            $table->unsignedBigInteger('created_by');         // -> users.id
            $table->unsignedBigInteger('updated_by')->nullable(); // -> users.id

            // Timestamps (nullable by default)
            $table->timestamps();

            // Indexes (short names to avoid 64-char limit)
            $table->index(['stockable_type', 'stockable_id'], 'acc_stocks_stockable_type_stockable_id_index');
            $table->index('company_id',  'acc_stocks_company_idx');
            $table->index('product_id',  'acc_stocks_product_idx');
            $table->index('created_by',  'acc_stocks_created_by_idx');
            $table->index('updated_by',  'acc_stocks_updated_by_idx');
            $table->index('date',        'acc_stocks_date_idx');
            $table->index('branch_id',   'acc_stocks_branch_idx');
            $table->index('warehouse_id','acc_stocks_wh_idx');
        });
    }

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