<?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::table('users', function (Blueprint $table): void {
            $table->unsignedInteger('ai_credits_balance')->default(3)->after('trial_ends_at');
        });

        Schema::create('credit_products', function (Blueprint $table): void {
            $table->ulid('id')->primary();
            $table->string('name');
            $table->text('description')->nullable();
            $table->string('type', 32);
            $table->unsignedInteger('credits');
            $table->unsignedInteger('amount');
            $table->string('currency', 3)->default('eur');
            $table->string('stripe_product_id')->nullable()->index();
            $table->string('stripe_price_id')->nullable()->unique();
            $table->boolean('is_active')->default(true)->index();
            $table->unsignedInteger('sort_order')->default(0);
            $table->timestamps();

            $table->index(['type', 'is_active', 'sort_order']);
        });

        Schema::create('credit_ledger_entries', function (Blueprint $table): void {
            $table->ulid('id')->primary();
            $table->foreignUlid('user_id')->constrained('users')->cascadeOnDelete();
            $table->foreignUlid('credit_product_id')->nullable()->constrained('credit_products')->nullOnDelete();
            $table->string('type', 64);
            $table->integer('credits');
            $table->unsignedInteger('balance_after');
            $table->string('source')->nullable()->unique();
            $table->string('stripe_checkout_session_id')->nullable()->index();
            $table->string('stripe_invoice_id')->nullable()->index();
            $table->string('stripe_payment_intent_id')->nullable()->index();
            $table->string('stripe_subscription_id')->nullable()->index();
            $table->json('metadata')->nullable();
            $table->timestamps();

            $table->index(['user_id', 'created_at']);
            $table->index(['user_id', 'type', 'created_at']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('credit_ledger_entries');
        Schema::dropIfExists('credit_products');

        Schema::table('users', function (Blueprint $table): void {
            $table->dropColumn('ai_credits_balance');
        });
    }
};
