<?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('games', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique(); // يُستخدم برابط الدعوة
            $table->string('type')->default('rps'); // نوع اللعبة (لعبة ثانية بالمستقبل)

            $table->foreignId('creator_id')->constrained('users')->cascadeOnDelete();
            $table->foreignId('opponent_id')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('winner_id')->nullable()->constrained('users')->nullOnDelete();

            $table->decimal('bet_amount', 18, 2);
            $table->decimal('commission_percent', 5, 2)->default(10.00);
            $table->decimal('commission_amount', 18, 2)->nullable();
            $table->decimal('payout_amount', 18, 2)->nullable();

            // نتيجة كل جولة حية (قبل ما تُحسم) — تُصفّر بعد كل جولة تُحسم
            $table->string('pending_creator_choice')->nullable();
            $table->string('pending_opponent_choice')->nullable();

            $table->unsignedTinyInteger('creator_wins')->default(0);
            $table->unsignedTinyInteger('opponent_wins')->default(0);
            $table->unsignedTinyInteger('round_number')->default(1); // الجولة الحالية (تزيد فقط بعد جولة حاسمة)

            $table->string('status')->default('waiting'); // waiting|in_progress|completed|cancelled
            $table->timestamp('expires_at')->nullable(); // لو محدا انضم قبلها، تُلغى تلقائياً
            $table->timestamps();

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

        Schema::create('game_rounds', function (Blueprint $table) {
            $table->id();
            $table->foreignId('game_id')->constrained()->cascadeOnDelete();
            $table->unsignedTinyInteger('round_number');
            $table->string('creator_choice');
            $table->string('opponent_choice');
            $table->foreignId('round_winner_id')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
        });
    }

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