<?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('artwork_downloads', function (Blueprint $table) {
            if (! Schema::hasColumn('artwork_downloads', 'ip_address')) {
                $table->string('ip_address', 45)->nullable()->after('ip');
            }

            if (! Schema::hasColumn('artwork_downloads', 'referer')) {
                $table->text('referer')->nullable()->after('user_agent');
            }

            if (! Schema::hasColumn('artwork_downloads', 'created_at')) {
                $table->timestamp('created_at')->useCurrent();
            }
        });

        try {
            Schema::table('artwork_downloads', function (Blueprint $table) {
                $table->index('created_at', 'artwork_downloads_created_at_idx');
            });
        } catch (\Throwable) {
            // Index may already exist depending on historical migration state.
        }
    }

    public function down(): void
    {
        try {
            Schema::table('artwork_downloads', function (Blueprint $table) {
                $table->dropIndex('artwork_downloads_created_at_idx');
            });
        } catch (\Throwable) {
            // Ignore when index is absent.
        }

        Schema::table('artwork_downloads', function (Blueprint $table) {
            if (Schema::hasColumn('artwork_downloads', 'ip_address')) {
                $table->dropColumn('ip_address');
            }

            if (Schema::hasColumn('artwork_downloads', 'referer')) {
                $table->dropColumn('referer');
            }

        });
    }
};
