<?php

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

return new class extends Migration
{
    public function up()
    {
        Schema::create('orders', function (Blueprint $table) {
            $table->id();
            
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->unsignedInteger('currency_id');
            $table->foreign('currency_id')->references('id')->on('currencies')->onDelete('cascade');
            
            // Order details
            $table->enum('type', ['market', 'pending']);
            $table->enum('side', ['buy', 'sell']);
            $table->decimal('open_price', 20, 8)->nullable();
            $table->decimal('close_price', 20, 8)->nullable();

            $table->decimal('amount', 20, 8);
            $table->decimal('volume', 20, 8)->nullable(); // Price * Amount
            
            // Order status and timing
            $table->enum('status', ['open', 'pending', 'closed']);
            $table->dateTime('open_time')->nullable();
            $table->dateTime('close_time')->nullable();
            $table->dateTime('expiry_time')->nullable(); // For limit orders
            
            // Take profit and stop loss
            $table->decimal('take_profit', 20, 8)->nullable();
            $table->decimal('stop_loss', 20, 8)->nullable();
            $table->boolean('is_trailing_stop')->default(false);
            $table->decimal('trailing_stop_distance', 20, 8)->nullable();
            
            // Execution details
            $table->decimal('executed_price', 20, 8)->nullable();
            $table->decimal('executed_amount', 20, 8)->nullable();
            $table->decimal('remaining_amount', 20, 8)->nullable();
            
            // Fees
            $table->decimal('fee', 20, 8)->nullable();
            $table->string('fee_currency')->nullable();
            
            $table->timestamps();
            $table->softDeletes();
            
            // Indexes
            $table->index(['user_id', 'status']);
            $table->index(['currency_id', 'status']);
        });
    }

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