<?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('risk_pools', function (Blueprint $table) {
            $table->id();
            $table->foreignId('draw_id')->constrained('draws')->cascadeOnDelete();
            $table->char('normalized_number', 4);
            $table->bigInteger('total_cap_amount')->default(0);
            $table->bigInteger('locked_amount')->default(0);
            $table->bigInteger('remaining_amount')->default(0);
            $table->unsignedTinyInteger('sold_out_status')->default(0);
            $table->unsignedBigInteger('version')->default(0);
            $table->timestamps();

            $table->unique(['draw_id', 'normalized_number'], 'uk_risk_pools_draw_number');
            $table->index(['draw_id', 'sold_out_status'], 'idx_risk_pools_draw_soldout');
        });

        Schema::create('risk_pool_lock_logs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('draw_id')->constrained('draws')->cascadeOnDelete();
            $table->char('normalized_number', 4);
            $table->foreignId('ticket_item_id')->nullable()->constrained('ticket_items')->nullOnDelete();
            $table->string('action_type', 16);
            $table->bigInteger('amount')->default(0);
            $table->string('source_reason', 32)->nullable();
            $table->timestamp('created_at')->useCurrent();

            $table->index(['draw_id', 'normalized_number'], 'idx_risk_lock_logs_draw_number');
        });
    }

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