<?php

declare(strict_types=1);

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

/**
 * User Statistics v2 – in-place schema upgrade.
 *
 * Renames legacy columns, widens all counters to unsignedBigInteger,
 * and adds creator-received metrics + activity timestamps.
 *
 * Mapping:
 *   uploads        → uploads_count
 *   downloads      → downloads_received_count
 *   pageviews      → artwork_views_received_count
 *   awards         → awards_received_count
 *   profile_views  → profile_views_count
 *
 * New columns added:
 *   favorites_received_count, comments_received_count,
 *   reactions_received_count, last_upload_at, last_active_at
 *
 * followers_count / following_count already exist with correct naming – only
 * widened to bigint.
 */
return new class extends Migration
{
    public function up(): void
    {
        // ── 1. Rename legacy columns ─────────────────────────────────────────
        Schema::table('user_statistics', function (Blueprint $table) {
            if (Schema::hasColumn('user_statistics', 'uploads')) {
                $table->renameColumn('uploads', 'uploads_count');
            }
            if (Schema::hasColumn('user_statistics', 'downloads')) {
                $table->renameColumn('downloads', 'downloads_received_count');
            }
            if (Schema::hasColumn('user_statistics', 'pageviews')) {
                $table->renameColumn('pageviews', 'artwork_views_received_count');
            }
            if (Schema::hasColumn('user_statistics', 'awards')) {
                $table->renameColumn('awards', 'awards_received_count');
            }
            if (Schema::hasColumn('user_statistics', 'profile_views')) {
                $table->renameColumn('profile_views', 'profile_views_count');
            }
        });

        // ── 2. Widen to unsignedBigInteger + add new columns ─────────────────
        Schema::table('user_statistics', function (Blueprint $table) {
            // Widen existing counters
            $table->unsignedBigInteger('uploads_count')->default(0)->change();
            $table->unsignedBigInteger('downloads_received_count')->default(0)->change();
            $table->unsignedBigInteger('artwork_views_received_count')->default(0)->change();
            $table->unsignedBigInteger('awards_received_count')->default(0)->change();
            $table->unsignedBigInteger('profile_views_count')->default(0)->change();
            $table->unsignedBigInteger('followers_count')->default(0)->change();
            $table->unsignedBigInteger('following_count')->default(0)->change();

            // Add new creator-received counters
            if (! Schema::hasColumn('user_statistics', 'favorites_received_count')) {
                $table->unsignedBigInteger('favorites_received_count')->default(0)->after('awards_received_count');
            }
            if (! Schema::hasColumn('user_statistics', 'comments_received_count')) {
                $table->unsignedBigInteger('comments_received_count')->default(0)->after('favorites_received_count');
            }
            if (! Schema::hasColumn('user_statistics', 'reactions_received_count')) {
                $table->unsignedBigInteger('reactions_received_count')->default(0)->after('comments_received_count');
            }

            // Activity timestamps
            if (! Schema::hasColumn('user_statistics', 'last_upload_at')) {
                $table->timestamp('last_upload_at')->nullable()->after('reactions_received_count');
            }
            if (! Schema::hasColumn('user_statistics', 'last_active_at')) {
                $table->timestamp('last_active_at')->nullable()->after('last_upload_at');
            }
        });

        // ── 3. Optional: indexes for creator ranking ─────────────────────────
        try {
            Schema::table('user_statistics', function (Blueprint $table) {
                $table->index('awards_received_count', 'idx_us_awards');
            });
        } catch (\Throwable) {}

        try {
            Schema::table('user_statistics', function (Blueprint $table) {
                $table->index('favorites_received_count', 'idx_us_favorites');
            });
        } catch (\Throwable) {}
    }

    public function down(): void
    {
        // Remove added columns
        Schema::table('user_statistics', function (Blueprint $table) {
            foreach (['favorites_received_count', 'comments_received_count', 'reactions_received_count', 'last_upload_at', 'last_active_at'] as $col) {
                if (Schema::hasColumn('user_statistics', $col)) {
                    $table->dropColumn($col);
                }
            }
        });

        // Drop indexes
        Schema::table('user_statistics', function (Blueprint $table) {
            try { $table->dropIndex('idx_us_awards'); } catch (\Throwable) {}
            try { $table->dropIndex('idx_us_favorites'); } catch (\Throwable) {}
        });

        // Rename back
        Schema::table('user_statistics', function (Blueprint $table) {
            if (Schema::hasColumn('user_statistics', 'uploads_count')) {
                $table->renameColumn('uploads_count', 'uploads');
            }
            if (Schema::hasColumn('user_statistics', 'downloads_received_count')) {
                $table->renameColumn('downloads_received_count', 'downloads');
            }
            if (Schema::hasColumn('user_statistics', 'artwork_views_received_count')) {
                $table->renameColumn('artwork_views_received_count', 'pageviews');
            }
            if (Schema::hasColumn('user_statistics', 'awards_received_count')) {
                $table->renameColumn('awards_received_count', 'awards');
            }
            if (Schema::hasColumn('user_statistics', 'profile_views_count')) {
                $table->renameColumn('profile_views_count', 'profile_views');
            }
        });
    }
};
