<?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
    {
        if (Schema::hasTable('leaderboards')) return;
        
        Schema::create('leaderboards', function (Blueprint $table) {
            $table->id();
            $table->string('type');
            $table->string('period');
            $table->date('period_start');
            $table->date('period_end');
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->integer('rank');
            $table->decimal('score', 15, 2)->default(0);
            $table->json('metadata')->nullable();
            $table->string('region')->nullable();
            $table->string('country')->nullable();
            $table->timestamps();
            
            $table->unique(['type', 'period', 'period_start', 'user_id'], 'leaderboard_unique');
            $table->index(['type', 'period', 'rank']);
            $table->index('country');
        });

        if (!Schema::hasTable('currency_rates')) {
            Schema::create('currency_rates', function (Blueprint $table) {
                $table->id();
                $table->string('from_currency', 3);
                $table->string('to_currency', 3);
                $table->decimal('rate', 20, 10);
                $table->timestamp('fetched_at');
                $table->timestamps();
                
                $table->unique(['from_currency', 'to_currency']);
            });
        }
    }

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

