<?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('broker_accounts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('broker', 50)->default('flattrade');
            $table->string('client_id')->nullable();
            $table->text('access_token')->nullable();
            $table->timestamp('token_expires_at')->nullable();
            $table->boolean('is_connected')->default(false);
            $table->timestamp('last_synced_at')->nullable();
            $table->timestamps();
        });

        Schema::create('strategies', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('name')->default('NIFTY Option Buying');
            $table->json('rulebook');
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

        Schema::create('bot_settings', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->boolean('bot_enabled')->default(false);
            $table->boolean('auto_trade')->default(false);
            $table->string('bot_status', 30)->default('idle');
            $table->string('scan_side', 10)->nullable();
            $table->timestamp('last_scan_at')->nullable();
            $table->timestamp('started_at')->nullable();
            $table->timestamps();
        });

        Schema::create('instruments', function (Blueprint $table) {
            $table->id();
            $table->string('exchange', 10);
            $table->string('token', 20);
            $table->string('tradingsymbol');
            $table->string('underlying', 30)->default('NIFTY');
            $table->date('expiry_date')->nullable();
            $table->decimal('strike_price', 12, 2)->nullable();
            $table->string('option_type', 5)->nullable();
            $table->unsignedInteger('lot_size')->default(1);
            $table->decimal('tick_size', 8, 4)->default(0.05);
            $table->boolean('is_active')->default(true);
            $table->timestamps();

            $table->unique(['exchange', 'token']);
            $table->index(['underlying', 'expiry_date', 'strike_price', 'option_type'], 'instruments_scan_idx');
        });

        Schema::create('market_ticks', function (Blueprint $table) {
            $table->id();
            $table->foreignId('instrument_id')->constrained()->cascadeOnDelete();
            $table->decimal('ltp', 12, 2)->nullable();
            $table->decimal('open', 12, 2)->nullable();
            $table->decimal('high', 12, 2)->nullable();
            $table->decimal('low', 12, 2)->nullable();
            $table->decimal('close', 12, 2)->nullable();
            $table->unsignedBigInteger('volume')->default(0);
            $table->unsignedBigInteger('oi')->default(0);
            $table->decimal('bid_price', 12, 2)->nullable();
            $table->decimal('ask_price', 12, 2)->nullable();
            $table->timestamp('tick_at');
            $table->timestamps();

            $table->index(['instrument_id', 'tick_at']);
        });

        Schema::create('option_greeks', function (Blueprint $table) {
            $table->id();
            $table->foreignId('instrument_id')->constrained()->cascadeOnDelete();
            $table->decimal('delta', 10, 6)->nullable();
            $table->decimal('gamma', 10, 6)->nullable();
            $table->decimal('theta', 10, 6)->nullable();
            $table->decimal('vega', 10, 6)->nullable();
            $table->decimal('iv', 10, 4)->nullable();
            $table->decimal('score', 8, 2)->nullable();
            $table->timestamp('computed_at');
            $table->timestamps();

            $table->index(['instrument_id', 'computed_at']);
        });

        Schema::create('intraday_candles', function (Blueprint $table) {
            $table->id();
            $table->foreignId('instrument_id')->constrained()->cascadeOnDelete();
            $table->unsignedSmallInteger('interval_minutes')->default(1);
            $table->timestamp('candle_at');
            $table->decimal('open', 12, 2);
            $table->decimal('high', 12, 2);
            $table->decimal('low', 12, 2);
            $table->decimal('close', 12, 2);
            $table->unsignedBigInteger('volume')->default(0);
            $table->timestamps();

            $table->unique(['instrument_id', 'interval_minutes', 'candle_at']);
        });

        Schema::create('bot_signals', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->foreignId('instrument_id')->nullable()->constrained()->nullOnDelete();
            $table->string('signal_type', 30);
            $table->string('regime', 30)->nullable();
            $table->decimal('confidence', 5, 2)->nullable();
            $table->json('conditions_met')->nullable();
            $table->text('reason')->nullable();
            $table->timestamps();
        });

        Schema::create('orders', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->foreignId('instrument_id')->nullable()->constrained()->nullOnDelete();
            $table->string('broker_order_no')->nullable();
            $table->string('exchange', 10);
            $table->string('tradingsymbol');
            $table->string('transaction_type', 5);
            $table->string('product_type', 5);
            $table->string('price_type', 10);
            $table->unsignedInteger('quantity');
            $table->decimal('price', 12, 2)->nullable();
            $table->decimal('trigger_price', 12, 2)->nullable();
            $table->decimal('avg_price', 12, 2)->nullable();
            $table->unsignedInteger('filled_quantity')->default(0);
            $table->string('status', 30)->default('PENDING');
            $table->string('remarks')->nullable();
            $table->timestamp('placed_at')->nullable();
            $table->timestamps();

            $table->index(['user_id', 'status']);
        });

        Schema::create('positions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->foreignId('instrument_id')->nullable()->constrained()->nullOnDelete();
            $table->string('exchange', 10);
            $table->string('tradingsymbol');
            $table->string('product_type', 5);
            $table->integer('net_quantity');
            $table->decimal('net_avg_price', 12, 2)->default(0);
            $table->decimal('ltp', 12, 2)->nullable();
            $table->decimal('unrealized_pnl', 14, 2)->default(0);
            $table->decimal('realized_pnl', 14, 2)->default(0);
            $table->decimal('price_factor', 12, 6)->default(1);
            $table->decimal('peak_ltp', 12, 2)->nullable();
            $table->boolean('is_open')->default(true);
            $table->timestamp('opened_at')->nullable();
            $table->timestamp('closed_at')->nullable();
            $table->timestamps();

            $table->index(['user_id', 'is_open']);
        });

        Schema::create('notifications', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('type', 50);
            $table->string('title');
            $table->text('message');
            $table->json('meta')->nullable();
            $table->timestamp('read_at')->nullable();
            $table->timestamps();
        });

        Schema::create('trade_journal', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->foreignId('instrument_id')->nullable()->constrained()->nullOnDelete();
            $table->string('regime', 30)->nullable();
            $table->json('entry_conditions')->nullable();
            $table->decimal('entry_price', 12, 2)->nullable();
            $table->decimal('exit_price', 12, 2)->nullable();
            $table->decimal('pnl', 14, 2)->nullable();
            $table->decimal('confidence', 5, 2)->nullable();
            $table->timestamp('entered_at')->nullable();
            $table->timestamp('exited_at')->nullable();
            $table->timestamps();
        });

        Schema::create('system_settings', function (Blueprint $table) {
            $table->id();
            $table->string('key')->unique();
            $table->json('value')->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('system_settings');
        Schema::dropIfExists('trade_journal');
        Schema::dropIfExists('notifications');
        Schema::dropIfExists('positions');
        Schema::dropIfExists('orders');
        Schema::dropIfExists('bot_signals');
        Schema::dropIfExists('intraday_candles');
        Schema::dropIfExists('option_greeks');
        Schema::dropIfExists('market_ticks');
        Schema::dropIfExists('instruments');
        Schema::dropIfExists('bot_settings');
        Schema::dropIfExists('strategies');
        Schema::dropIfExists('broker_accounts');
    }
};
