<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

return new class extends Migration {
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        if (Schema::hasTable('subscription_logs')) {
            return;
        }

        Schema::create('subscription_logs', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('subscription_id');
            $table->unsignedInteger('member_id')->nullable();
            $table->unsignedInteger('admin_user_id')->nullable();
            $table->string('action_type', 50);
            $table->text('action_description');
            $table->json('old_values')->nullable();
            $table->json('new_values')->nullable();
            $table->json('metadata')->nullable();
            $table->enum('source', ['admin', 'customer', 'system', 'api'])->default('system');
            $table->string('ip_address', 45)->nullable();
            $table->text('user_agent')->nullable();
            $table->timestamps();

            // Foreign key constraints
            $table->foreign('subscription_id')
                ->references('id')
                ->on('subscriptions')
                ->onDelete('cascade')
                ->onUpdate('cascade');

            $table->foreign('member_id')
                ->references('id')
                ->on('members')
                ->onDelete('set null')
                ->onUpdate('cascade');

            // Indexes for performance
            $table->index(['subscription_id', 'created_at']);
            $table->index(['action_type', 'created_at']);
            $table->index(['member_id', 'created_at']);
            $table->index('source');
        });
    }

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