<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('ticket_items', function (Blueprint $table) {
            $table->id();
            $table->string('ticket_no', 64)->unique();
            $table->foreignId('order_id')->constrained('ticket_orders')->cascadeOnDelete();
            $table->foreignId('player_id')->constrained('players')->cascadeOnDelete();
            $table->foreignId('draw_id')->constrained('draws')->cascadeOnDelete();
            $table->string('original_number', 32)->nullable();
            $table->char('normalized_number', 4);
            $table->string('play_code', 32);
            $table->unsignedTinyInteger('dimension')->nullable()->comment('2/3/4');
            $table->unsignedTinyInteger('digit_slot')->nullable()->comment('千百十个位，领域字典');
            $table->string('bet_mode', 32)->nullable();
            $table->bigInteger('unit_bet_amount')->default(0);
            $table->bigInteger('total_bet_amount')->default(0);
            $table->decimal('rebate_rate_snapshot', 8, 4)->default(0);
            $table->decimal('commission_rate_snapshot', 8, 4)->default(0);
            $table->bigInteger('actual_deduct_amount')->default(0);
            $table->json('odds_snapshot_json')->nullable();
            $table->json('rule_snapshot_json')->nullable();
            $table->unsignedInteger('combination_count')->default(1);
            $table->bigInteger('estimated_max_payout')->default(0);
            $table->bigInteger('risk_locked_amount')->default(0);
            $table->string('status', 32);
            $table->string('fail_reason_code', 32)->nullable();
            $table->string('fail_reason_text', 255)->nullable();
            $table->bigInteger('win_amount')->default(0);
            $table->bigInteger('jackpot_win_amount')->default(0);
            $table->timestamp('settled_at')->nullable();
            $table->timestamps();

            $table->index(['player_id', 'draw_id'], 'idx_ticket_items_player_draw');
            $table->index(['draw_id', 'status'], 'idx_ticket_items_draw_status');
            $table->index(['draw_id', 'normalized_number'], 'idx_ticket_items_draw_number');
        });
    }

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