<?php

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
    {
        if (!Schema::hasTable('subscriptions')) {
            Schema::create('subscriptions', function (Blueprint $table) {
                $table->id();
                $table->foreignId('user_id')->constrained('users')->onDelete('cascade');
                $table->foreignId('plan_id')->constrained('subscription_plans')->onDelete('restrict');
                $table->unsignedBigInteger('payment_method_id')->nullable(); // Foreign key will be added in separate migration
                $table->enum('status', ['active', 'canceled', 'expired', 'past_due', 'trialing'])->default('active');
                $table->timestamp('started_at');
                $table->timestamp('expires_at')->nullable();
                $table->timestamp('next_billing_date')->nullable();
                $table->timestamp('canceled_at')->nullable();
                $table->text('cancel_reason')->nullable();
                $table->string('payment_gateway')->nullable(); // stripe, paypal, etc.
                $table->string('gateway_subscription_id')->nullable(); // External subscription ID
                $table->timestamps();
                
                $table->index(['user_id', 'status']);
                $table->index('expires_at');
                $table->index('next_billing_date');
            });
        }
    }

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