<?php

use App\Models\Package;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('checkout_sessions', function (Blueprint $table) {
            $table->uuid('id')->primary();

            $table->foreignIdFor(User::class)->nullable()->constrained()->nullOnDelete();
            $table->foreignIdFor(Tenant::class)->nullable()->constrained()->nullOnDelete();
            $table->foreignIdFor(Package::class)->constrained()->cascadeOnDelete();

            $table->json('package_snapshot');

            $table->string('status', 40)->default('draft');
            $table->string('provider', 30)->default('none');
            $table->json('status_history')->nullable();

            $table->char('currency', 3)->default('EUR');
            $table->decimal('amount_subtotal', 10, 2)->default(0);
            $table->decimal('amount_total', 10, 2)->default(0);

            $table->string('stripe_payment_intent_id')->nullable();
            $table->string('stripe_customer_id')->nullable();
            $table->string('stripe_subscription_id')->nullable();
            $table->string('paddle_checkout_id')->nullable();
            $table->string('paddle_transaction_id')->nullable();
            $table->json('provider_metadata')->nullable();

            $table->string('locale', 5)->nullable();
            $table->timestamp('expires_at')->nullable();
            $table->timestamp('completed_at')->nullable();
            $table->text('failure_reason')->nullable();

            $table->timestamps();
            $table->softDeletes();

            $table->unique('stripe_payment_intent_id');
            $table->unique('paddle_checkout_id');
            $table->unique('paddle_transaction_id');
            $table->index(['provider', 'status']);
            $table->index('expires_at');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('checkout_sessions');
    }
};
