<?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('event_purchases')) {
            Schema::create('event_purchases', function (Blueprint $table) {
                $table->id();
                $table->foreignId('tenant_id')->constrained()->cascadeOnDelete();
                $table->unsignedInteger('events_purchased')->default(1);
                $table->decimal('amount', 10, 2)->default(0);
                $table->string('currency', 3)->default('EUR');
                $table->string('provider', 32);
                $table->string('external_receipt_id')->nullable()->index();
                $table->string('status', 32)->default('pending');
                $table->timestamp('purchased_at')->nullable();
                $table->timestamps();
                $table->index(['tenant_id', 'purchased_at']);
            });
        }

        if (! Schema::hasTable('event_credits_ledger')) {
            Schema::create('event_credits_ledger', function (Blueprint $table) {
                $table->id();
                $table->foreignId('tenant_id')->constrained()->cascadeOnDelete();
                $table->integer('delta');
                $table->string('reason', 64);
                $table->foreignId('related_purchase_id')->nullable()->constrained('event_purchases')->nullOnDelete();
                $table->text('note')->nullable();
                $table->timestamps();
                $table->index(['tenant_id', 'created_at']);
            });
        }
    }

    public function down(): void
    {
        if (app()->environment('local', 'testing')) {
            Schema::dropIfExists('event_purchases');
            Schema::dropIfExists('event_credits_ledger');
        }
    }
};
