<?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
    {
        Schema::table('subscriptions', function (Blueprint $table) {
            // Provider tracking
            $table->string('provider', 50)->default('stripe')->after('user_id');
            $table->string('provider_subscription_id')->nullable()->after('stripe_id');

            // Unified status tracking
            $table->string('unified_status', 50)->default('active')->after('stripe_status');
            $table->timestamp('cancelled_at')->nullable()->after('trial_ends_at');
            $table->string('cancellation_reason')->nullable()->after('cancelled_at');
            $table->timestamp('paused_at')->nullable()->after('cancellation_reason');
            $table->timestamp('resumed_at')->nullable()->after('paused_at');

            // Migration tracking
            $table->string('migration_batch_id')->nullable()->after('resumed_at');
            $table->boolean('is_migrated')->default(false)->after('migration_batch_id');
            $table->json('legacy_data')->nullable()->after('is_migrated');

            // Sync and audit
            $table->timestamp('synced_at')->nullable()->after('legacy_data');
            $table->json('provider_data')->nullable()->after('synced_at');
            $table->timestamp('last_provider_sync')->nullable()->after('provider_data');

            // Indexes
            $table->index('provider');
            $table->index('provider_subscription_id');
            $table->index('unified_status');
            $table->index('is_migrated');
            $table->index('migration_batch_id');
            $table->index('synced_at');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('subscriptions', function (Blueprint $table) {
            $table->dropIndex(['provider']);
            $table->dropIndex(['provider_subscription_id']);
            $table->dropIndex(['unified_status']);
            $table->dropIndex(['is_migrated']);
            $table->dropIndex(['migration_batch_id']);
            $table->dropIndex(['synced_at']);

            $table->dropColumn([
                'provider',
                'provider_subscription_id',
                'unified_status',
                'cancelled_at',
                'cancellation_reason',
                'paused_at',
                'resumed_at',
                'migration_batch_id',
                'is_migrated',
                'legacy_data',
                'synced_at',
                'provider_data',
                'last_provider_sync',
            ]);
        });
    }
};
